<template>
  <div class="order">
    <!-- 下单操作面板 -->
    <div class="order-form" v-show="isFolding">
      <i-form>
        <div class="left">
          <!-- 选择合约 -->
          <FormItem
            :label="$t('trade.contract')"
            class="order-item selectContract"
            :label-width="55"
          >
            <i-select
              style="width: 134px;"
              v-model="nowConCode"
              :disabled="isLock"
              @on-change="selectContract"
              :placeholder="$t('trade.selectContract')"
            >
              <i-option
                v-for="item in contractlist"
                :value="item.heyue_id"
                :key="item.heyue_id"
                >{{ item.heyue_name }}</i-option
              >
            </i-select>
            <div
              :class="['conlock', { unlock: !isLock }]"
              @click="isLock = !isLock"
            ></div>
          </FormItem>
          <!-- 手数 -->
          <FormItem
            :label="$t('trade.number')"
            class="order-item"
            :label-width="55"
          >
            <!-- <i-input type="number" v-model="hands" :placeholder="$t('trade.number')">
						<div class="handle-group" slot="suffix">
							<span class="adjust up" @click="figureUp(1, 1)"></span>
							<span class="adjust down" :style="{ cursor: hands === 1 ? 'not-allowed' : 'pointer' }"
								@click="figureUp(1, 0)"></span>
						</div>
					</i-input> -->
            <InputNumber size="small" v-model="hands" :min="1"></InputNumber>
          </FormItem>
          <!-- 价格 -->
          <!-- :label="$t('trade.price')" -->
          <FormItem
            :label="$t('trade.price')"
            class="order-item"
            :label-width="55"
          >
            <!-- <i-select v-model="priceType"
						:placeholder="priceType === '2' ? $t('trade.marketPrice') : $t('trade.restingOrder')">
						<i-option :value="'1'">{{ $t('trade.rivalPrice') }}</i-option>
						<i-option :value="'2'">{{ $t('trade.marketPrice') }}</i-option>
						<i-option :value="'3'">{{ $t('trade.latestPrice') }}</i-option>
						<i-option :value="'4'">{{ $t('trade.restingOrder') }}</i-option>
					</i-select> -->

            <div v-if="priceType === '4'" class="pricetipbox">
              <!-- <i-select slot="label" class="tipbox1" v-model="priceTypeIcon" placeholder="<=">
								<i-option :value="'1'">{{ $t('trade.rivalPrice') }}</i-option>
								<i-option v-for="item in priceTypeIconList" :key="item.key" :value="item.key">{{
									item.value
								}}</i-option>
							</i-select> -->
              <!-- <i-input style="width: 100%; margin-top: 6px;flex: 4;" type="number" v-model="btnPrice"
							:placeholder="$t('trade.restingOrder')">

							<span class="el-icon-minus hand-icon"
								:style="{ cursor: nowMinimum === 0 ? 'not-allowed' : 'pointer' }"
								@click="figureUp(2, 0)" slot="prefix"></span>
							<span class="el-icon-plus hand-icon"
								:style="{ cursor: nowMinimum === 0 ? 'not-allowed' : 'pointer' }"
								@click="figureUp(2, 1)" slot="suffix"></span>
						</i-input> -->
              <InputNumber
                size="small"
                v-model="btnPrice"
                :precision="accuracy"
                @change="btnPriceChange"
                :step="Number(nowMinimum)"
                :min="0"
                :placeholder="$t('trade.restingOrder')"
              ></InputNumber>
            </div>
            <div class="typePrice" v-else>
              <span v-show="priceType == 2">{{ $t("trade.marketPrice") }}</span>
              <span v-show="priceType == 1">{{ $t("trade.rivalPrice") }}</span>
              <span v-show="priceType == 3">{{ $t("trade.latestPrice") }}</span>
            </div>
            <div class="select">
              <div
                :class="{ selectBtn: true, selectBtnActive: priceType === '2' }"
                @click="priceType = '2'"
              >
                {{ $t("trade.marketPrice") }}
              </div>
              <div
                :class="{ selectBtn: true, selectBtnActive: priceType === '4' }"
                @click="priceType = '4'"
              >
                {{ $t("trade.restingOrder") }}
              </div>
              <div
                :class="{ selectBtn: true, selectBtnActive: priceType === '1' }"
                @click="priceType = '1'"
              >
                {{ $t("trade.rivalPrice") }}
              </div>
              <div
                :class="{ selectBtn: true, selectBtnActive: priceType === '3' }"
                @click="priceType = '3'"
              >
                {{ $t("trade.latestPrice") }}
              </div>
            </div>
          </FormItem>
        </div>
        <div :class="{ right: true, rightActive: !stopFlag }">
          <!-- 止盈/止损点数 -->
          <div class="profit-loss">
            <MyCheckbox v-model="stopFlag" class="stopCheckbox">{{
              $t("trade.profitLoss")
            }}</MyCheckbox>
            <FormItem
              :label="$t('trade.limitedN')"
              :class="['order-item', { 'is-disabled': !stopFlag }]"
              :label-width="62"
            >
              <InputNumber
                size="mini"
                v-model="stopScore"
                @change="handleStopScore"
                :min="0"
                :disabled="!stopFlag"
                :width="100"
                :jiajianW="24"
                :height="24"
              ></InputNumber>
            </FormItem>
            <FormItem
              :label-width="62"
              :label="$t('trade.stopN')"
              :class="['order-item', 'ml6', { 'is-disabled': !stopFlag }]"
            >
              <InputNumber
                size="mini "
                v-model="stopLoss"
                @change="handleStopLoss"
                :min="0"
                :disabled="!stopFlag"
                :jiajianW="24"
                :width="100"
                :height="24"
              ></InputNumber>
            </FormItem>
            <!-- <FormItem :label="$t('trade.limitedN')" class="order-item">
							<i-input type="number" v-model="stopScore" @on-change="handleStopScore"
								:placeholder="$t('trade.score')">
								<div class="handle-group" slot="suffix">
									<span class="adjust up" @click="figureUp(3, 1)"></span>
									<span class="adjust down"
										:style="{ cursor: stopScore === 0 ? 'not-allowed' : 'pointer' }"
										@click="figureUp(3, 0)"></span>
								</div>
							</i-input>
						</FormItem>
						<FormItem :label="$t('trade.stopN')" class="order-item ml6">
							<i-input type="number" v-model="stopLoss" @on-change="handleStopLoss"
								:placeholder="$t('trade.score')">
								<div class="handle-group" slot="suffix">
									<span class="adjust up" @click="figureUp(4, 1)"></span>
									<span class="adjust down"
										:style="{ cursor: stopLoss === 0 ? 'not-allowed' : 'pointer' }"
										@click="figureUp(4, 0)"></span>
								</div>
							</i-input>
						</FormItem> -->
          </div>
        </div>
      </i-form>

      <div class="btn-goup">
        <div class="handle-btn buy-price" @click="buyin">
          <!-- 对手价 -->
          <div class="price-num" v-if="priceType === '1'">{{ latestSell }}</div>
          <!-- 市价 -->
          <div class="price-num" v-if="priceType === '2'">
            {{ $t("trade.marketPrice") }}
          </div>
          <!-- 最新价 -->
          <div class="price-num" v-if="priceType === '3'">
            {{ latestPrice }}
          </div>
          <!-- 挂单价 -->
          <div class="price-num" v-if="priceType === '4'">{{ btnPrice }}</div>
          <!-- 手动价格 -->
          <!-- <div class="price-num" v-if="priceType === '5'">{{nowPrice}}</div>-->
          <div class="btn-msg">{{ $t("trade.buy") }}</div>
        </div>
        <div class="handle-btn sell-price" @click="sellOut">
          <!-- 对手价 -->
          <div class="price-num" v-if="priceType === '1'">{{ latestBuy }}</div>
          <!-- 市价 -->
          <div class="price-num" v-if="priceType === '2'">
            {{ $t("trade.marketPrice") }}
          </div>
          <!-- 最新价 -->
          <div class="price-num" v-if="priceType === '3'">
            {{ latestPrice }}
          </div>
          <!-- 挂单价 -->
          <div class="price-num" v-if="priceType === '4'">{{ btnPrice }}</div>
          <!-- 手动价格 -->
          <!--<div class="price-num" v-if="priceType === '5'">{{nowPrice}}</div>-->
          <div class="btn-msg">{{ $t("trade.sell") }}</div>
        </div>
        <div
          class="handle-btn close-price"
          :class="handleClass"
          @click="closeOut"
        >
          <!-- 对手价 -->
          <div class="price-num" v-if="priceType === '1'">
            {{ latestPrice }}
          </div>
          <!-- 市价 -->
          <div class="price-num" v-if="priceType === '2'">
            {{ $t("trade.marketPrice") }}
          </div>
          <!-- 最新价 -->
          <div class="price-num" v-if="priceType === '3'">
            {{ latestPrice }}
          </div>
          <!-- 挂单价 -->
          <div class="price-num" v-if="priceType === '4'">{{ btnPrice }}</div>
          <!-- 手动价格 -->
          <!--<div class="price-num" v-if="priceType === '5'">{{nowPrice}}</div>-->

          <div class="btn-msg" v-if="isbuy === '1'">
            {{ $t("trade.close") }}买
          </div>
          <div class="btn-msg" v-else-if="isbuy === '2'">
            {{ $t("trade.close") }}卖
          </div>
          <div class="btn-msg" v-else>{{ $t("trade.close") }}买</div>
        </div>
      </div>
    </div>
    <!-- 折叠条,用于折叠下单操作面板 -->
    <div
      class="folding-strip"
      :class="{ expand: !isFolding }"
      @click="isFolding = !isFolding"
    >
      <span class="fold-icon"></span>
    </div>
    <!-- 订单列表 -->
    <div class="order-table">
      <!-- 持仓列表 -->
      <div class="position">
        <div class="header-handle">
          <div class="left">
            <!-- 全部平仓 -->
            <span class="btn" @click="operationAll(1)">{{
              $t("trade.allClose")
            }}</span>
            <!-- 快捷平仓 -->
            <span class="btn" @click="quickClosing(1)">{{
              $t("trade.quickClose")
            }}</span>
            <!-- 快捷反手 -->
            <span class="btn" @click="Backhand">{{
              $t("trade.quickBackhand")
            }}</span>
            <!-- 快捷锁仓 -->
            <span class="btn" @click="quickLock">{{
              $t("trade.quickLock")
            }}</span>
            <!-- 修改止盈止损 -->
            <span
              class="btn"
              v-if="posRadio === '1'"
              @click="modifyTheStopLoss1"
              >{{ $t("trade.editLimitStop") }}</span
            >
            <span
              class="btn"
              v-if="posRadio === '2'"
              @click="modifyTheStopLoss2"
              >{{ $t("trade.editLimitStop") }}</span
            >
            <!-- 更改标识 -->
            <!-- <span class="btn" @click="editbiaoshi">{{$t('trade.editbiaoshi')}}</span> -->
            <!-- <el-input  class="biaoshi" v-model="biaoshi" :placeholder="$t('trade.showbiaoshi')"/> -->
          </div>
          <div class="right">
            <el-radio
              v-model="posRadio"
              label="1"
              @change="handleChangeRadio('1')"
              >{{ $t("trade.displayDetail") }}</el-radio
            >
            <el-radio
              v-model="posRadio"
              label="2"
              @change="handleChangeRadio('2')"
              >{{ $t("trade.summaryDisplay") }}</el-radio
            >
          </div>
        </div>
        <div class="table-box">
          <table border="0" cellspacing="0" cellpadding="0" class="dTable">
            <thead>
              <tr>
                <th>{{ $t("trade.contract") }}</th>
                <th @click="sortposlist('Business')">
                  {{ $t("trade.transition") }}
                </th>
                <th>{{ $t("trade.position") }}</th>
                <th @click="sortposlist('AveragePrice')">
                  {{ $t("trade.openPrice") }}
                </th>
                <th>{{ $t("capital.computedDetailProfitAndLoss") }}</th>
                <th>{{ $t("capital.jiacha") }}</th>
                <th>{{ $t("trade.stopPrice") }}</th>
                <th>{{ $t("trade.stopLossAmount") }}</th>
                <th>{{ $t("trade.takeProfitPrice") }}</th>
                <th>{{ $t("trade.takeProfitAmount") }}</th>
                <!-- <th v-if="posRadio === '1'" @click="sortposlist('Biaoshi')">{{$t('trade.biaoshi')}}</th>-->
              </tr>
            </thead>
            <!-- 明细列表 -->
            <tbody v-if="posRadio === '1'">
              <!-- 无数据展示 -->
              <tr v-if="sortshowPosList.length === 0" class="noneInfo">
                <td>{{ this.$t("msg.noEntrustRecord") }}</td>
              </tr>
              <!-- 数据列表 -->
              <tr
                v-else
                v-for="(item, index) in sortshowPosList"
                :key="item.ID"
                :class="{ active: index === ponIndex }"
                @click="switchPosTr(index, item)"
                @dblclick="quickClosing(2)"
              >
                <!-- 合约名称 -->
                <td>
                  <div v-if="item.Name">{{ item.Name }}</div>
                  <div v-else>--</div>
                </td>
                <!-- 买卖 -->
                <td>
                  <div
                    v-if="item.Business"
                    :class="{
                      red: item.Business == '买',
                      green: item.Business == '卖',
                    }"
                  >
                    {{ item.Business }}
                  </div>
                  <div v-else>--</div>
                </td>
                <!-- 持仓量 -->
                <td>
                  <div v-if="item.Quantity">{{ item.Quantity }}</div>
                  <div v-else>--</div>
                </td>
                <!-- 开仓价 -->
                <td>
                  <div v-if="item.AveragePrice">{{ item.AveragePrice }}</div>
                  <div v-else>--</div>
                </td>
                <!-- 逐笔盈浮 -->
                <td>
                  <div
                    v-if="item.Floating"
                    :class="{
                      pricerise: parseFloat(item.Floating) > 0,
                      pricefall: parseFloat(item.Floating) < 0,
                    }"
                  >
                    {{ item.Floating }}
                  </div>
                  <div v-else>--</div>
                </td>
                <!-- 盈利价差 -->
                <td>
                  <div
                    v-if="item.jiacha"
                    :class="{
                      pricerise: parseFloat(item.jiacha) > 0,
                      pricefall: parseFloat(item.jiacha) < 0,
                    }"
                  >
                    {{ item.jiacha }}
                  </div>
                  <div v-else>--</div>
                </td>
                <!-- 止损点位 -->
                <td>
                  <div
                    v-if="
                      fullstoplist[item.ID] && fullstoplist[item.ID].LossPoint
                    "
                  >
                    {{ fullstoplist[item.ID].LossPoint }}
                  </div>
                  <div v-else>--</div>
                </td>
                <!-- 止损金额 -->
                <td>
                  <div
                    v-if="
                      fullstoplist[item.ID] && fullstoplist[item.ID].LossAmount
                    "
                  >
                    {{ fullstoplist[item.ID].LossAmount }}
                  </div>
                  <div v-else>--</div>
                </td>
                <!-- 止盈点位 -->
                <td>
                  <div
                    v-if="
                      fullstoplist[item.ID] && fullstoplist[item.ID].ProfitPoint
                    "
                  >
                    {{ fullstoplist[item.ID].ProfitPoint }}
                  </div>
                  <div v-else>--</div>
                </td>
                <!-- 止盈金额 -->
                <td>
                  <div
                    v-if="
                      fullstoplist[item.ID] &&
                        fullstoplist[item.ID].ProfitAmount
                    "
                  >
                    {{ fullstoplist[item.ID].ProfitAmount }}
                  </div>
                  <div v-else>--</div>
                </td>
                <!-- 标识 -->
                <!-- 
								<td>
									<div v-if="item.Biaoshi">{{item.Biaoshi}}</div>
									<div v-else>--</div>
								</td> -->
              </tr>
            </tbody>
            <!-- 汇总信息 -->
            <tbody v-if="posRadio === '2'">
              <!-- 无数据展示 -->
              <tr v-if="sortshowCollectList.length === 0" class="noneInfo">
                <td>{{ this.$t("msg.noEntrustRecord") }}</td>
              </tr>
              <!-- 数据列表 -->
              <tr
                v-else
                v-for="(item, index) in sortshowCollectList"
                :key="item.ID"
                :class="{ active: index === ponIndex }"
                @click="switchPosTr(index, item)"
                @dblclick="quickClosing(2)"
              >
                <!-- 合约名称 -->
                <td>
                  <div v-if="item.Name">{{ item.Name }}</div>
                  <div v-else>--</div>
                </td>
                <!-- 买卖 -->
                <td>
                  <div v-if="item.Business">{{ item.Business }}</div>
                  <div v-else>--</div>
                </td>
                <!-- 持仓量 -->
                <td>
                  <div v-if="item.Quantity">{{ item.Quantity }}</div>
                  <div v-else>--</div>
                </td>
                <!-- 开仓价 -->
                <td>
                  <div v-if="item.AveragePrice">{{ item.AveragePrice }}</div>
                  <div v-else>--</div>
                </td>
                <!-- 逐笔盈浮 -->
                <td>
                  <div
                    v-if="collectFloat[item.BusCode][item.ContractID]"
                    :class="{
                      pricerise:
                        parseFloat(
                          collectFloat[item.BusCode][item.ContractID]
                        ) > 0,
                      pricefall:
                        parseFloat(
                          collectFloat[item.BusCode][item.ContractID]
                        ) < 0,
                    }"
                  >
                    {{ collectFloat[item.BusCode][item.ContractID].toFixed(2) }}
                  </div>
                  <div v-else>--</div>
                </td>
                <!-- 汇总价差 -->
                <td>
                  <div
                    v-if="collectJiacha[item.BusCode][item.ContractID]"
                    :class="{
                      pricerise:
                        parseFloat(
                          collectJiacha[item.BusCode][item.ContractID]
                        ) > 0,
                      pricefall:
                        parseFloat(
                          collectJiacha[item.BusCode][item.ContractID]
                        ) < 0,
                    }"
                  >
                    {{
                      collectJiacha[item.BusCode][item.ContractID].toFixed(2)
                    }}
                  </div>
                  <div v-else>--</div>
                </td>
                <!-- 汇总 止损点位 -->
                <td>
                  <div
                    v-if="
                      fullstoplists[item.ContractID] &&
                        fullstoplists[item.ContractID].LossPoint &&
                        fullstoplists[item.ContractID].Business ===
                          item.Business
                    "
                  >
                    {{ fullstoplists[item.ContractID].LossPoint }}
                  </div>
				  <div
				    v-else-if="
				      fullstoplists1[item.ContractID] &&
				        fullstoplists1[item.ContractID].LossPoint &&
				        fullstoplists1[item.ContractID].Business ===
				          item.Business
				    "
				  >
				    {{ fullstoplists1[item.ContractID].LossPoint }}
				  </div>
                  <div v-else>--</div>
                </td>
                <!-- 汇总 止损金额 -->
                <td>
                  <div
                    v-if="
                      fullstoplists[item.ContractID] &&
                        fullstoplists[item.ContractID].LossAmount &&
                        fullstoplists[item.ContractID].Business ===
                          item.Business
                    "
                  >
                    {{ fullstoplists[item.ContractID].LossAmount }}
                  </div>
				  <div
				    v-else-if="
				      fullstoplists1[item.ContractID] &&
				        fullstoplists1[item.ContractID].LossAmount &&
				        fullstoplists1[item.ContractID].Business ===
				          item.Business
				    "
				  >
				    {{ fullstoplists1[item.ContractID].LossAmount }}
				  </div>
                  <div v-else>--</div>
                </td>
                <!-- 汇总 止盈点位 -->
                <td>
                  <div
                    v-if="
                      fullstoplists[item.ContractID] &&
                        fullstoplists[item.ContractID].ProfitPoint &&
                        fullstoplists[item.ContractID].Business ===
                          item.Business
                    "
                  >
                    {{ fullstoplists[item.ContractID].ProfitPoint }}
                  </div>
				  <div
				    v-else-if="
				      fullstoplists1[item.ContractID] &&
				        fullstoplists1[item.ContractID].ProfitPoint &&
				        fullstoplists1[item.ContractID].Business ===
				          item.Business
				    "
				  >
				    {{ fullstoplists1[item.ContractID].ProfitPoint }}
				  </div>
                  <div v-else>--</div>
                </td>
                <!-- 汇总 止盈金额 -->
                <td>
                  <div
                    v-if="
                      fullstoplists[item.ContractID] &&
                        fullstoplists[item.ContractID].ProfitAmount &&
                        fullstoplists[item.ContractID].Business ===
                          item.Business
                    "
                  >
                    {{ fullstoplists[item.ContractID].ProfitAmount }}
                  </div>
				  <div
				    v-else-if="
				      fullstoplists1[item.ContractID] &&
				        fullstoplists1[item.ContractID].ProfitAmount &&
				        fullstoplists1[item.ContractID].Business ===
				          item.Business
				    "
				  >
				    {{ fullstoplists1[item.ContractID].ProfitAmount }}
				  </div>
                  <div v-else>--</div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      <!-- 委托列表 -->
      <div class="commission">
        <div class="header-handle">
          <div class="left">
            <span class="btn" @click="operationAll(2)">{{
              $t("trade.allCancelOrder")
            }}</span>
            <span class="btn" @click="withdrawal">{{
              $t("trade.cancelOrder")
            }}</span>
            <el-radio
              v-model="comRadio"
              label="1"
              @change="weituoChangeRadio('1')"
              >{{ $t("trade.displayCanCancel") }}</el-radio
            >
            <el-radio
              v-model="comRadio"
              label="2"
              @change="weituoChangeRadio('2')"
              >{{ $t("trade.displayAll") }}</el-radio
            >
            <!--<span class="btn">{{$t('trade.editLimitStop')}}</span>-->
          </div>
        </div>
        <div class="table-box">
          <table border="0" cellspacing="0" cellpadding="0" class="dTable">
            <thead>
              <tr>
                <th>{{ $t("trade.contract") }}</th>
                <th>{{ $t("trade.status") }}</th>
                <th>{{ $t("trade.transition") }}</th>
                <th>{{ $t("trade.openClose") }}</th>
                <th>{{ $t("trade.entrustPrice") }}</th>
                <th>{{ $t("trade.entrustType") }}</th>
                <th>{{ $t("trade.entrustVol") }}</th>
                <th>{{ $t("trade.averagePrice") }}</th>
                <th>{{ $t("trade.numbering") }}</th>
                <th>{{ $t("trade.entrustTime") }}</th>
                <th>{{ $t("trade.dealTime") }}</th>
              </tr>
            </thead>
            <tbody>
              <!-- 无数据时展示 -->
              <tr v-if="weituoList.length === 0" class="noneInfo">
                <td>{{ $t("msg.noData") }}</td>
              </tr>
              <!-- 数据列表 -->
              <tr
                v-else
                v-for="(item, index) in weituoList"
                :key="item.Numbering"
                :class="{ active: index === comIndex }"
                @click="switchComTr(index)"
              >
                <!-- 合约名称 -->
                <td>
                  <div v-if="item.Name" :title="item.Name">{{ item.Name }}</div>
                  <div v-else>--</div>
                </td>
                <!-- 状态 -->
                <td>
                  <div v-if="item.Status">{{ item.Status }}</div>
                  <div v-else>--</div>
                </td>
                <!-- 买卖 -->
                <td>
                  <div v-if="item.Business">{{ item.Business }}</div>
                  <div v-else>--</div>
                </td>
                <!-- 开平 -->
                <td>
                  <div v-if="item.Kaiping">{{ item.Kaiping }}</div>
                  <div v-else>--</div>
                </td>
                <!-- 委托价 -->
                <td>
                  <div v-if="item.ReportPrice">{{ item.ReportPrice }}</div>
                  <div v-else>--</div>
                </td>
                <!-- 委托类型 -->
                <td>
                  <div v-if="item.Category">{{ item.Category }}</div>
                  <div v-else>--</div>
                </td>
                <!-- 委托量 -->
                <td>
                  <div v-if="item.ReportHand">{{ item.ReportHand }}</div>
                  <div v-else>--</div>
                </td>
                <!-- 成交均价 -->
                <td>
                  <div v-if="item.AveragePrice">{{ item.AveragePrice }}</div>
                  <div v-else>--</div>
                </td>
                <!-- 委托号 -->
                <td :title="item.Numbering">
                  <div v-if="item.Numbering">{{ item.Numbering }}</div>
                  <div v-else>--</div>
                </td>
                <!-- 委托时间 -->
                <td>
                  <div
                    v-if="item.DateTime && item.DateTime !== '0'"
                    :title="item.DateTime"
                  >
                    {{ item.DateTime }}
                  </div>
                  <div v-else>--</div>
                </td>
                <!-- 成交时间 -->
                <td>
                  <div
                    v-if="item.LastTime && item.LastTime !== '0'"
                    :title="item.LastTime"
                  >
                    {{ item.LastTime }}
                  </div>
                  <div v-else>--</div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <!-- 修改止盈止损 -->
    <el-dialog
      :visible="showPaL"
      width="570px"
      top="25vh"
      :close-on-click-modal="false"
      :append-to-body="true"
      @close="dialogClose"
      custom-class="full-stop"
    >
      <div slot="title" class="dialog-title">{{ $t("trade.settingPL") }}</div>
      <div class="dialog-content">
        <h4 class="fontbold">
          <span
            >{{ $t("trade.contract") }}：{{
              sortshowPosList[ponIndex] === undefined
                ? ""
                : sortshowPosList[ponIndex].Name
            }}</span
          >
          <!-- <span>{{$t('trade.position')}}：{{showPosList[ponIndex] === undefined ? '' : showPosList[ponIndex].Quantity}}</span> -->
          <div class="quantity-block">
            <label class="label">{{ $t("trade.position") }}:</label>
            <div class="content">
              <input type="text" class="content-input" v-model="quanNum" />
            </div>
            <div class="num-btn">
              <span class="btn up" @click="calcPostion(1)"></span>
              <span class="btn down" @click="calcPostion(0)"></span>
            </div>
          </div>
          <span
            >{{ $t("trade.dir") }}：{{
              sortshowPosList[ponIndex] === undefined
                ? ""
                : sortshowPosList[ponIndex].Business
            }}</span
          >
        </h4>
        <div class="setting-form">
          <div class="form-item">
            <!-- 止盈价位 -->
            <div class="input-block">
              <label class="label">{{ $t("trade.takeProfitPrice") }}</label>
              <div class="content">
                <input
                  type="text"
                  class="content-input"
                  @input="conversion($event, 1)"
                  v-model="profitPrice"
                />
              </div>
              <div class="num-btn">
                <span class="btn up" @click="regulation(1, 1)"></span>
                <span class="btn down" @click="regulation(1, 0)"></span>
              </div>
            </div>
            <!-- 止盈金额 -->
            <div class="input-block">
              <label class="label">{{ $t("trade.takeProfitAmount") }}</label>
              <div class="content">
                <input
                  type="text"
                  class="content-input"
                  @input="conversion($event, 2)"
                  v-model="profitAmount"
                />
              </div>
              <div class="num-btn">
                <span class="btn up" @click="regulation(2, 1)"></span>
                <span class="btn down" @click="regulation(2, 0)"></span>
              </div>
            </div>
          </div>
          <div class="form-item">
            <!-- 止损价位 -->
            <div class="input-block">
              <label class="label">{{ $t("trade.stopPrice") }}</label>
              <div class="content">
                <input
                  type="text"
                  class="content-input"
                  @input="conversion($event, 3)"
                  v-model="stopPrice"
                />
              </div>
              <div class="num-btn">
                <span class="btn up" @click="regulation(3, 1)"></span>
                <span class="btn down" @click="regulation(3, 0)"></span>
              </div>
            </div>
            <!-- 止损金额 -->
            <div class="input-block">
              <label class="label">{{ $t("trade.stopLossAmount") }}</label>
              <div class="content">
                <input
                  type="text"
                  class="content-input"
                  @input="conversion($event, 4)"
                  v-model="lossAmount"
                />
              </div>
              <div class="num-btn">
                <span class="btn up" @click="regulation(4, 1)"></span>
                <span class="btn down" @click="regulation(4, 0)"></span>
              </div>
            </div>
          </div>
          <div class="error-msg" v-if="plError !== ''">{{ plError }}</div>
        </div>
        <div class="condi-type">
          <div class="condi-name">{{ $t("tip.description") }}：</div>
          <div class="clear">
            1、{{ $t("tip.matter1") }}
            <br />
            2、{{ $t("tip.matter2") }}
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <!-- 删除 -->
        <!-- <button
          type="button"
          v-if="showPLdel"
          class="delete"
          @click="deletePL"
        >{{$t('trade.delete')}}</button> -->
        <!-- 确认 -->
        <button type="button" class="save" @click="submitProfitLoss()">
          {{ $t("tip.save") }}
        </button>
        <!-- 取消 -->
        <button type="button" class="cancle" @click="dialogClose">
          {{ $t("tip.cancel") }}
        </button>
      </div>
    </el-dialog>
    <!-- 确认下单提示 -->
    <el-dialog
      :visible="orderTip"
      width="28vw"
      top="25vh"
      :append-to-body="true"
      custom-class="tips-alert"
      @close="orderTip = false"
    >
      <div slot="title" class="dialog-title">{{ $t("tip.confirm") }}</div>
      <div class="dialog-content">
        <img class="dialog-icon" src="../../../assets/img/dialog-sure.png" />
        <span class="dialog-msg"
          >{{ $t("trade.contract") }}：{{ orderObj.heyue_name }}，
          {{ $t("trade.number") }}：{{ hands }}， {{ tradeType }}：{{
            tipPrice
          }}，{{ $t("trade.whetOrder") }}？</span
        >
      </div>
      <div slot="footer" class="dialog-footer">
        <!-- 确认 -->
        <button class="confirm-btn btn-sure" @click="handleBtns">
          <span>{{ $t("login.confirm") }}</span>
        </button>
        <!-- 取消 -->
        <div class="confirm-btn btn-cancel" @click.stop="orderTip = false">
          <span>{{ $t("tip.cancel") }}</span>
        </div>
      </div>
    </el-dialog>

		<settingPLlist
			:showPalist="showPalist"
			:limit="limit"
			:currentPage1="currentPage1"
			@modifyTheStopLoss="modifyTheStopLoss"
			@removeStopLoss="removeStopLoss"
			@handleAddSetlist="handleAddSetlist"
			@dialogClose="dialogClose2"
			@handlePage="handlePage"
			@handlePageSize="handlePageSize"
			:close-on-click-modal="false"
			:append-to-body="true"
		>
		</settingPLlist>
	</div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import * as trade from "../../../request/trade";
import settingPLlist from "./settingPLlist";
import store from "../../../store";
import {
  Form,
  FormItem,
  Select,
  Option,
  Checkbox,
  Input,
  Dropdown,
  DropdownMenu,
  DropdownItem,
} from "iview";
import InputNumber from "../../../components/InputNumber/InputNumber.vue";
import MyCheckbox from "../../../components/MyCheckbox.vue";
import { unlink } from "fs";
import { obtainLength, throttle } from "../../../utils/auth";
import { log } from "console";
export default {
  name: "Order",
  components: {
    FormItem,
    IForm: Form,
    ISelect: Select,
    IOption: Option,
    IInput: Input,
    Dropdown,
    DropdownMenu,
    DropdownItem,
    settingPLlist,
    Checkbox,
    InputNumber,
    MyCheckbox,
  },
	data() {
		return {
      stopFlag: false,
      addPoIndex: 0,
      addFlag: false,
      showPalist: false, // 修改止盈止损列表
      limit: 6,
      currentPage1: 1,
      total: 0,
      listData: [], // 向子组建传参
      nowConCode: "", // 当前组件自留合约代码(下单表单中)
      hands: 1, // 手数,最小1笔 (下单表单中)
      biaoshi: "", // 标识
      nowPrice: "", // 当前价格(下单表单中)
      stopScore: 0, // 止盈点数 (下单表单中)
      stopLoss: 0, // 止损点数 (下单表单中)
      latestPrice: 0, // 当前组件选择的合约的最新价，根据行情更新(表单中使用)
      latestBuy: 0, // 当前组件选择的合约的买价，根据行情更新(表单中使用)
      latestSell: 0, // 当前组件选择的合约的卖价，根据行情更新(表单中使用)
      priceType: "2", // 当前选中的价格类型: 1对手价2市价3最新价4挂单价
      priceTypeIcon: 0, // 客户指定价位时提交标志
      priceTypeIconList: [
        { key: 0, value: "<=" },
        { key: 1, value: ">=" },
      ],
      isLock: false, // 是否锁定合约种类 true 为锁定
      isFolding: true, // 左侧表单面板伸缩切换
      nowMinimum: 0, // 当前选中的合约的最小波动(左侧表单中)
      accuracy: 0, // 挂单价精度
      btnPrice: 0, // 挂单价时按钮中的价格
      isCal: false, // 用户是否进行加减操作
      posRadio: "1", // 持仓操作，明细/汇总切换
      comRadio: "1",
      // ponIndex: -1, // 持仓单选中
      comIndex: -1, // 委托单选中
      showPosList: [], // 当前显示的持仓列表
      showCollectList: [], // 当前汇总持仓列表
      floatingList: {}, // 浮盈数据存储
      jiachaList: {}, // 价差数据存储
      collectFloat: {}, // 汇总浮盈数据
      collectJacha: {}, // 汇总价差浮盈数据
      showPaL: false, // 设置止盈止损弹出窗
      profitPrice: 0, // 止盈价位
      profitAmount: 0, // 止盈金额
      stopPrice: 0, // 止损价位
      lossAmount: 0, // 止损金额
      fullstopId: 0, // 止盈止损id
      plError: "", // 设置止盈止损错误信息
      consbType: 1,
      orderTip: false, // 下单确认提示
      orderObj: {}, // 当前下单的合约信息
      tradeType: "买入", // 交易类型
      tipPrice: 0, // 提示价格
      quanNum: 1, // 设置止盈止损手数
      showPLdel: false, // 是否展示止盈止损的删除功能
      weituo_flag: 1, //显示可撤和全部
      sort_flag: 0, //排序标志
      sort_column: "ID", //排序列
    };
  },
	mounted() {
		// this.stopScore = localStorage.zhiying ? localStorage.zhiying : 0
		// this.stopLoss = localStorage.zhisun ? localStorage.zhisun : 0
		this.nowConCode = this.contractlist[0].heyue_id; // 合约默认选择第一个

		this.$store.dispatch(
			"panel/updateSelname",
			this.contractlist[0].heyue_name
		);
		
		//console.log("sssss",fullstoplists);
		//console.log("dddd",fullstoplists1);
	},

	computed: {
		...mapGetters([
			"setList",
			"positionlist",
			"commissionlist",
			"contractlist",
			"actcontract",
			"fullstoplist",
			"fullstoplistsz",//汇总止盈止损列表
			"fullstoplist2",
			"fullfenyelist",
			"latestMarket",
			"delogEve",
			"dbclickEve",
			"productlist",
			"ponIndex",
			"isbuy",
		]),
		
		//汇总的止盈止损列表（买）（同种合约只取最后一个）
		fullstoplists() {
			let temp_lists = []
			this.fullstoplistsz.map((v)=>{
				if(v.Business==='买'){
					temp_lists[v.ContractId] = v
				}
			})
			return temp_lists
		},
		
		//汇总的止盈止损列表（卖）（同种合约只取最后一个）
		fullstoplists1() {
			let temp_lists = []
			this.fullstoplistsz.map((v)=>{
				if(v.Business==='卖'){
					temp_lists[v.ContractId] = v
				}
			})
			return temp_lists
		},

    handleClass() {
      if (this.ponIndex === -1) {
        return ["buy-disable"];
      }
      if (this.posRadio === "1") {
        if (
          this.showPosList[this.ponIndex] !== undefined &&
          this.showPosList[this.ponIndex].CanBeFlat <= 0
        ) {
          return ["buy-disable"];
        }
        // console.log(this.nowConCode);
        if (
          this.showPosList[this.ponIndex] &&
          this.showPosList[this.ponIndex].ContractID !== this.nowConCode
        ) {
          return ["buy-disable"];
        }
      } else {
        if (
          this.showCollectList[this.ponIndex] !== undefined &&
          this.showCollectList[this.ponIndex].CanBeFlat <= 0
        ) {
          return ["buy-disable"];
        }
        // console.log(this.nowConCode);
        if (
          this.showCollectList[this.ponIndex] &&
          this.showCollectList[this.ponIndex].ContractID !== this.nowConCode
        ) {
          return ["buy-disable"];
        }
      }

      return [];
    },
    cancelList() {
      let temp_list;
      temp_list = this.commissionlist.filter((item) => {
        return item.cancel_flag == 1;
      });

      return temp_list;
    },
    weituoList() {
      if (this.weituo_flag == 1) {
        return this.cancelList;
      } else {
        return this.commissionlist;
      }
    },
    sortshowPosList() {
      if (this.sort_flag == 0) {
        return this.showPosList.sort((a, b) => {
          var x = a[this.sort_column];
          var y = b[this.sort_column];
          return x > y ? -1 : x < y ? 1 : 0;
        });
      } else if (this.sort_flag == 1) {
        return this.showPosList.sort((a, b) => {
          var x = a[this.sort_column];
          var y = b[this.sort_column];
          return x < y ? -1 : x > y ? 1 : 0;
        });
      } else {
        return this.showPosList.sort((a, b) => {
          var x = a[this.sort_column];
          var y = b[this.sort_column];
          return x > y ? -1 : x < y ? 1 : 0;
        });
      }
    },
    sortshowCollectList() {
      if (this.sort_flag == 0) {
        return this.showCollectList;
      } else if (this.sort_flag == 1) {
        if (this.sort_column != "Biaoshi") {
          return this.showCollectList.sort((a, b) => {
            var x = a[this.sort_column];
            var y = b[this.sort_column];
            return x < y ? -1 : x > y ? 1 : 0;
          });
        }
      } else {
        if (this.sort_column != "Biaoshi") {
          return this.showCollectList.sort((a, b) => {
            var x = a[this.sort_column];
            var y = b[this.sort_column];
            return x > y ? -1 : x < y ? 1 : 0;
          });
        }
      }
    },
  },
	watch: {
	stopFlag(newVal, oldVal) {
	  if (!newVal) {
	    this.stopLoss = 0;
	    this.stopScore = 0;
	  } else {
	    this.stopLoss = localStorage.zhisun || 0;
	    this.stopScore = localStorage.zhiying || 0;
	  }
	},

    setList: {
      handler(newVal) {
        let _actcontract =
          this.actcontract != null
            ? this.actcontract
            : this.contractlist[0].heyue_id;
        let _list = newVal;
        for (let i = 0; i < _list.length; i++) {
          if (_list[i][4] === _actcontract) {
            this.stopScore = _list[i][2];
            this.stopLoss = _list[i][3];
          }
        }
      },
      deep: true,
      immediate: true,
    },
    positionlist: {
      handler(newVal) {
        // 持仓列表
        // 判断当前选中的合约是否存在，如果不存在则清空
        if (
          !newVal[this.ponIndex] ||
          newVal[this.ponIndex].ContractID !== this.actcontract
        ) {
          this.$store.dispatch("panel/updatePonIndex", -1);
          // this.ponIndex = -1;
        }
        // 如果当前数据不存在或者数据为空数组，将当前展示的明细列表和汇总列表都置空
        if (!newVal || newVal.length === 0) {
          this.showPosList = [];
          this.showCollectList = [];
          return;
        }
        // console.log(newVal);
        // 利用map生成新数据存储地址，避免在vuex外改变状态
        // 明细持仓列表
        let newData = newVal.map((v) => {
          let nowObj = {
            ...v,
          };
          return nowObj;
        });
        this.showPosList = newData;
        this.showPosList.map((v) => {
          if (!this.$db.has("order" + v.ID + ".biaoshi").value()) v.Biaoshi = 0;
          else
            v.Biaoshi = this.$db
              .read()
              .get("order" + v.ID + ".biaoshi")
              .value();
        });
        this.getCollectList(newData);
        let bus1 = 0,
          bus2 = 0;
        let _list = [];
        if (this.posRadio === "1") {
          if (this.showPosList.length !== 0) {
            this.showPosList &&
              this.showPosList.map((item, i) => {
                if (item.ContractID == this.nowConCode) {
                  _list.push(this.showPosList[i]);
                }
              });
            let lenNum = _list;
            if (_list.length == 1) {
              this.showPosList &&
                this.showPosList.map((item, i) => {
                  if (item.ContractID == this.nowConCode) {
                    this.$store.dispatch(
                      "panel/updateIsbuy",
                      this.showPosList[i].BusCode
                    );
                    this.$store.dispatch("panel/updatePonIndex", i);
                  }
                });
            } else if (_list.length > 1) {
              for (let i = 0; i < _list.length; i++) {
                if (_list[i].BusCode == "1") {
                  bus1 += _list[i].Quantity;
                } else if (_list[i].BusCode == "2") {
                  bus2 += _list[i].Quantity;
                }
              }
              if (bus1 !== bus2) {
                for (let m = 0; m < this.showPosList.length; m++) {
                  if (this.showPosList[m].ContractID == this.nowConCode) {
                    // this.$store.commit("panel/SET_PONINDEX", i)
                    this.$store.dispatch(
                      "panel/updateIsbuy",
                      this.showPosList[m].BusCode
                    );
                    this.$store.dispatch("panel/updatePonIndex", m);
                    return false;
                  }
                }
              }
            }
          }
        } else {
          // 汇总显示-点击表格显示平买平卖
          if (this.showCollectList.length !== 0) {
            this.showCollectList &&
              this.showCollectList.map((item, i) => {
                if (item.ContractID == this.nowConCode) {
                  _list.push(this.showCollectList[i]);
                }
              });
            let lenNum = _list;
            if (_list.length == 1) {
              this.showCollectList &&
                this.showCollectList.map((item, i) => {
                  if (item.ContractID == this.nowConCode) {
                    this.$store.dispatch(
                      "panel/updateIsbuy",
                      this.showCollectList[i].BusCode
                    );
                    this.$store.dispatch("panel/updatePonIndex", i);
                  }
                });
            } else if (_list.length > 1) {
              for (let i = 0; i < _list.length; i++) {
                if (_list[i].BusCode == "1") {
                  bus1 += _list[i].Quantity;
                } else if (_list[i].BusCode == "2") {
                  bus2 += _list[i].Quantity;
                }
              }
              if (bus1 !== bus2) {
                for (let m = 0; m < this.showCollectList.length; m++) {
                  if (this.showCollectList[m].ContractID == this.nowConCode) {
                    // this.$store.commit("panel/SET_PONINDEX", i)
                    this.$store.dispatch(
                      "panel/updateIsbuy",
                      this.showCollectList[m].BusCode
                    );
                    this.$store.dispatch("panel/updatePonIndex", m);
                    return false;
                  }
                }
              }
            }
          }
        }
      },
      deep: true,
      immediate: true,
    },
    commissionlist: {
      handler(newVal) {
        // console.log('当前委托单接收', newVal)
        if (!newVal[this.comIndex]) {
          this.comIndex = -1;
        }
        /*
				this.cancelList = newVal.filter((item)=> {
					return item.cancel_flag==1
				})
				*/
      },
      deep: true,
      immediate: true,
    },
    actcontract: {
      handler(newVal, oldVal) {
        // console.log("当前合约id", newVal);
        // 这里是主页列表选中合约是否会影响当前合约变化
        if (newVal === undefined) {
          return;
        }
        // console.log(this.$store.getters.productlist.length)
        for (const item of this.productlist) {
          if (item.ContractID === newVal) {
            // console.log('当前合约名称： ' + item.Name)
            // console.log("当前合约最小波动： " + item.Minimum);
            this.nowMinimum = parseFloat(item.Minimum);
            this.accuracy = obtainLength(item.Minimum);
            // console.log('当前最小波动精度aa', this.accuracy)
          }
        }
        // 合约号无变化
        if (newVal === oldVal) {
          return;
        }
        // 如果为不锁定状态
        if (!this.isLock) {
          this.nowConCode = newVal;
        }
      },
      immediate: true, // 最初绑定值的时候也执行handler函数
    },
    latestMarket: {
      handler(newVal) {
        let that = this;
        let priceList = {}; // 最新价数据提取暂存
        //  console.log(this.nowConCode)
        for (const latest of newVal) {
          priceList[latest.heyue_id] = latest.currentPrice;
          // 更新左侧表单中选中的合约的最新价格
          // console.log('当前数据', latest)
          if (this.nowConCode === latest.heyue_id) {
            this.latestPrice = latest.currentPrice; // 最新价
            this.latestSell = latest.seller1; // 卖
            this.latestBuy = latest.buy1; // 买
          }
        }

        // 只有持仓列表有数据才执行
        if (this.showPosList.length === 0) {
          return;
        }

        // 先收集浮动盈亏的数据和合约id数据
        let floatList = [];
        let cIdList = new Set(); // 合约id集合
        // 遍历并计算浮动盈亏，将之存储
        let totalFloat = 0;
        let jiacha = 0;
        for (const item of this.showPosList) {
          let Floating = 0; // 当前浮盈
          let latestPrice = priceList[item.ContractID];
          let nowAcc = obtainLength(item.Minimum); // 当前合约根据最小波动得出的精度
          if (item.BusCode === "2") {
            // 卖: (开仓价 - 最新价 )* 持仓量 * 合约乘数
            Floating =
              (item.AveragePrice - latestPrice) *
              item.Quantity *
              item.Multiplier;
            jiacha = (item.AveragePrice - latestPrice).toFixed(nowAcc);
          } else if (item.BusCode === "1") {
            // 买: (最新价 - 开仓价 )* 持仓量 * 合约乘数
            Floating =
              (latestPrice - item.AveragePrice) *
              item.Quantity *
              item.Multiplier;
            jiacha = (latestPrice - item.AveragePrice).toFixed(nowAcc);
          }

          Floating = Floating.toFixed(2);

          // 明细浮盈
          that.floatingList[item.ID] = Floating;
          // 明细浮盈
          that.jiachaList[item.ID] = jiacha;

          // 汇总浮盈（先在循环中存储浮盈）
          let obj = {
            BusCode: item.BusCode, // 买卖方向
            ContractID: item.ContractID, // 合约id
            Quantity: item.Quantity, // 持仓量（手数）
            accuracy: nowAcc, // 最小波动精度
            Floating,
            jiacha,
          };
          totalFloat += Floating * 1;
          cIdList.add(item.ContractID);
          floatList.push(obj);
        }
        //console.log("明细浮动盈亏",floatList)
        this.$totalFloat = (totalFloat * 1).toFixed(2);
        // 更新浮盈状态
        const newFlList = this.showPosList.map((v) => {
          return {
            ...v,
            Floating: that.floatingList[v.ID],
            jiacha: that.jiachaList[v.ID],
          };
        });
        this.showPosList = newFlList;

        // 汇总浮盈（计算浮盈）
        //console.log('加买卖方向的浮盈：', floatList);
        let noRepeat = Array.from(cIdList); // 无重复set集合转成数组
        // console.log('无重复：',noRepeat)
        let collectFlist = {
          "1": {},
          "2": {},
        }; // 汇总浮盈计算后暂存: 定义1存储买方向 2存储卖方向
        let collectJlist = {
          "1": {},
          "2": {},
        }; // 汇总价差计算后暂存: 定义1存储买方向 2存储卖方向
        for (const item of noRepeat) {
          let buyFloating = 0; // 买方向浮盈
          let buyQua = 0; // 买方向手数
          let buyJiacha = 0; // 买方向价差
          let sellFloating = 0; // 卖方向浮盈
          let sellQua = 0; // 卖方向手数
          let sellJiacha = 0; // 卖方向价差
          // 遍历浮盈列表
          let collAcc = 0;
          for (const val of floatList) {
            collAcc = val.accuracy;
            // 买方向
            if (val.BusCode === "1" && val.ContractID === item) {
              buyFloating = buyFloating + val.Floating * 1;
              buyQua = buyQua + val.Quantity;
              buyJiacha = buyJiacha + val.jiacha * 1;
            }

            // 卖方向
            if (val.BusCode === "2" && val.ContractID === item) {
              sellFloating = sellFloating + val.Floating * 1;
              sellQua = sellQua + val.Quantity;
              sellJiacha = sellJiacha + val.jiacha * 1;
            }
          }

          // 归类存储
          collectFlist["1"][item] = buyFloating;
          collectFlist["2"][item] = sellFloating;
          collectJlist["1"][item] = buyJiacha;
          collectJlist["2"][item] = sellJiacha;
        }
        this.collectFloat = collectFlist;
        this.collectJiacha = collectJlist;
        //console.log('买卖方向浮盈汇总',collectFlist)
        //console.log('买卖方向浮盈汇总',collectJlist)
      },
      deep: true,
      immediate: true,
    },
    nowConCode: {
      handler(newVal, oldVal) {
        let _this = this;
        if (newVal === oldVal) {
          return;
        }
        // 合约变化后初始化各个值，更新最小波动
        this.priceType = "2";
        this.nowPrice = ""; // 当前价格(左侧表单中)
        this.hands = 1; // 手数,最小1笔
        this.stopScore = 0; // 止盈点数
        this.stopLoss = 0; // 止损点数
        // console.log(this.productlist);
        if (newVal === undefined || newVal === null) {
          return;
        }
        if (this.productlist.length === 0) return;
        let nowCobj = this.productlist.find((v) => v.ContractID === newVal);
        // console.log(nowCobj)
        if (nowCobj.Name) {
          /* this.$store.commit("panel/SET_SELNAME", nowCobj.Name); */
          this.$store.dispatch("panel/updateSelname", nowCobj.Name);
          if (this.setList) {
            var setList = this.setList;
            for (let i = 0; i < setList.length; i++) {
              if (setList[i][1] == nowCobj.Name) {
                this.stopScore = setList[i][2];
                this.stopLoss = setList[i][3];
              }
            }
          }
        }
      },
      immediate: true,
    },
    priceType(val) {
      this.isCal = false;
      if (val !== "1") {
        this.nowPrice = this.latestPrice;
      }
      if (val === "4") {
        this.btnPrice = this.latestPrice;
      }
    },
    profitPrice(val) {
      if (val === "" && this.profitAmount !== "") {
        this.profitAmount = "";
      }
    }, // 止盈价位
    profitAmount(val) {
      if (val === "" && this.profitPrice !== "") {
        this.profitPrice = "";
      }
    }, // 止盈金额
    stopPrice(val) {
      if (val === "" && this.lossAmount !== "") {
        this.lossAmount = "";
      }
    }, // 止损价位
    lossAmount(val) {
      if (val === "" && this.stopPrice !== "") {
        this.stopPrice = "";
      }
    }, // 止损金额
    showPaL(val) {
      if (!val) {
        this.profitPrice = 0; // 止盈价位
        this.profitAmount = 0; // 止盈金额
        this.stopPrice = 0; // 止损价位
        this.lossAmount = 0; // 止损金额
      }
    },
  },
  methods: {
    btnPriceChange(oldVal, newVal) {
      // 当前价格（单位：最小波动）
      this.isCal = true;
      // console.log("最小波动价格：" + this.nowMinimum);

      // priceType1对手价2市价3最新价4挂单价5调整后价格
      if (this.priceType !== "4") {
        this.priceType = "5";
      }
      if (this.nowPrice === "") {
        this.nowPrice = this.latestPrice;
      }
      this.nowPrice = this.nowPrice * 1;
      this.nowMinimum = this.nowMinimum * 1;
      console.log(this.nowMinimum);
      if (this.accuracy !== 0) {
        this.nowPrice = this.nowPrice.toFixed(this.accuracy);
      }
      // if (this.priceType === "4") {
      // 	this.btnPrice = this.nowPrice;
      // }
    },
    sortposlist(column) {
      if (this.sort_flag == 0) {
        this.sort_flag = 1;
      } else if (this.sort_flag == 1) {
        this.sort_flag = 2;
      } else {
        this.sort_flag = 1;
      }
      this.sort_column = column;
    },
    getCollectList(arr) {
      //console.log("当前传入", arr);
      let idArr = arr.map((v) => {
        if (v.BusCode === "买") {
          v.BusCode = "1";
        }
        if (v.BusCode === "卖") {
          v.BusCode = "2";
        }
        return v.ContractID;
      });
      let setArr = new Set(idArr);
      // 生成汇总持仓列表
      // 先数组去重,保证合约唯一
      let noRepeat = Array.from(setArr); // 无重复Set转换成数组
      let collectList = []; // 汇总数据
      //console.log("无重复数组", noRepeat);
      for (const val of noRepeat) {
        let buyObj = {}; // 买方向暂存
        let buyQuantity = 0; // 持仓量（买方向）
        let buyPrice = 0; // 价格汇总（买方向）

        let sellObj = {}; // 卖方向数据暂存
        let sellQuantity = 0; // 持仓量（卖方向）
        let sellPrice = 0; // 价格汇总（卖方向）

        let findArr = arr.find((item) => item.ContractID === val);

        let itemAcc = 0;
        for (const item of arr) {
          itemAcc = obtainLength(item.Minimum);
          //console.log("汇总精度", itemAcc);
          // 买方向数据筛选
          if (
            item.ContractID === val &&
            (item.BusCode === "1" || item.BusCode === "买")
          ) {
            buyObj = {
              ...item,
            };
            let bQua = parseFloat(item.Quantity);
            let bPri = parseFloat(item.AveragePrice);
            buyQuantity += bQua;
            buyPrice = buyPrice + bPri * bQua;
          }

          // 卖方向数据筛选
          if (
            item.ContractID === val &&
            (item.BusCode === "2" || item.BusCode === "卖")
          ) {
            sellObj = {
              ...item,
            };
            let sQua = parseFloat(item.Quantity);
            let sPri = parseFloat(item.AveragePrice);
            sellQuantity += sQua;
            sellPrice = sellPrice + sPri * sQua;
          }
        }
        // console.log("买方向：", buyObj);
        // console.log("卖方向：", sellObj);
        if (buyObj.ContractID) {
          buyObj.Quantity = buyQuantity;
          buyObj.AveragePrice = parseFloat(
            (buyPrice / buyQuantity).toFixed(itemAcc + 1)
          );
          collectList.push(buyObj);
        }

        if (sellObj.ContractID) {
          sellObj.Quantity = sellQuantity;
          sellObj.AveragePrice = parseFloat(
            (sellPrice / sellQuantity).toFixed(itemAcc + 1)
          );
          collectList.push(sellObj);
        }
      }
      //console.log("汇总2数据", collectList);
      this.showCollectList = collectList;
    },
    selectContract(id) {
      console.log(id);
      // 选中合约处理
      if (!this.isLock) {
        // 不锁定状态下，同时修改store和当前自留合约代码
        // this.$store.commit("product/SET_ACTCONTRACT", id);
        this.$store.dispatch("product/updateActcontract", id);
      }
    },
    switchPriceType(i) {
      this.priceType = parseInt(i);
    },
    switchPosTr(i, item) {
      // 持仓列表table表格选中事件
      if (this.posRadio === "1") {
        this.$store.dispatch("panel/updateIsbuy", this.showPosList[i].BusCode);
        if (this.isLock) {
          // 当前锁定，只改变table中的tr选中
          // this.ponIndex = i;
          this.$store.dispatch("panel/updatePonIndex", i);
        } else {
          // 未锁定，同时改变
          // this.$store.commit("product/SET_ACTCONTRACT", item.ContractID);
          this.$store.dispatch("product/updateActcontract", item.ContractID);
          // this.ponIndex = i;
          this.$store.dispatch("panel/updatePonIndex", i);
          if (this.showPosList[i].Quantity * 1 > 0) {
            this.hands = this.showPosList[i].Quantity;
          }
        }
      } else {
        this.$store.dispatch(
          "panel/updateIsbuy",
          this.showCollectList[i].BusCode
        );
        if (this.isLock) {
          // 当前锁定，只改变table中的tr选中
          // this.ponIndex = i;
          this.$store.dispatch("panel/updatePonIndex", i);
        } else {
          // 未锁定，同时改变
          // this.$store.commit("product/SET_ACTCONTRACT", item.ContractID);
          this.$store.dispatch("product/updateActcontract", item.ContractID);
          // this.ponIndex = i;
          this.$store.dispatch("panel/updatePonIndex", i);
          if (this.showCollectList[i].Quantity * 1 > 0) {
            this.hands = this.showCollectList[i].Quantity;
          }
        }
      }
    },
    switchComTr(i) {
      // 委托列表table表格选中事件
      this.comIndex = i;
    },
    // 止盈止损点缓存
    saveSetlist(val, index) {
      console.log(val, index);
      // 合约id 止盈止损点值 标识
      // index 1止盈点 0 止损点
      let _list = this.setList;
      let _actcontract =
        this.actcontract != null
          ? this.actcontract
          : this.contractlist[0].heyue_id;

      for (let i = 0; i < _list.length; i++) {
        if (_list[i][4] === _actcontract) {
          if (index == 1) {
            _list[i][2] = val;
          } else {
            _list[i][3] = val;
          }
        }
      }
      this.$store.dispatch("user/updateSetList", _list);
    },
    handleStopScore(event) {
      // console.log(event)
      console.log(this.stopScore);
      this.saveSetlist(this.stopScore, 1);
      localStorage.zhiying = this.stopScore;
    },
    handleStopLoss(event) {
      // console.log(this.stopLoss)
      this.saveSetlist(this.stopLoss, 0);
      localStorage.zhisun = this.stopLoss;
    },
    figureUp(type, isAdd) {
      // type 类型 isAdd 加减
      // 计算各个input的值增减
      switch (type) {
        case 1:
          // 计算手数（单位：1）
          this.hands = this.hands * 1;
          if (this.hands >= 1 && isAdd) {
            this.hands += 1;
          } else if (this.hands > 1 && !isAdd) {
            this.hands -= 1;
          }
          break;
        case 2:
          // 当前价格（单位：最小波动）
          this.isCal = true;
          // console.log("最小波动价格：" + this.nowMinimum);

          // priceType1对手价2市价3最新价4挂单价5调整后价格
          if (this.priceType !== "4") {
            this.priceType = "5";
          }
          if (this.nowPrice === "") {
            this.nowPrice = this.latestPrice;
          }
          this.nowPrice = this.nowPrice * 1;
          this.nowMinimum = this.nowMinimum * 1;
          if (this.nowPrice >= 0 && isAdd) {
            // 加
            this.nowPrice += this.nowMinimum;
          } else if (this.nowPrice > 0 && !isAdd) {
            if (this.nowPrice - this.nowMinimum >= 0) {
              this.nowPrice -= this.nowMinimum;
            }
          }
          if (this.accuracy !== 0) {
            this.nowPrice = this.nowPrice.toFixed(this.accuracy);
          }

          if (this.priceType === "4") {
            this.btnPrice = this.nowPrice;
          }
          break;
        case 3:
          // 止盈点数（单位：1）
          this.stopScore = this.stopScore * 1;
          if (this.stopScore >= 0 && isAdd) {
            this.stopScore += 1;
          } else if (this.stopScore > 0 && !isAdd) {
            this.stopScore -= 1;
          }
          this.saveSetlist(this.stopScore, 1);
          localStorage.zhiying = this.stopScore;
          break;
        case 4:
          // 止损点数（单位：1）
          this.stopLoss = this.stopLoss * 1;
          if (this.stopLoss >= 0 && isAdd) {
            this.stopLoss += 1;
          } else if (this.stopLoss > 0 && !isAdd) {
            this.stopLoss -= 1;
          }
          this.saveSetlist(this.stopLoss, 0);
          localStorage.zhisun = this.stopLoss;
          break;
      }
    },
    buyin: throttle(function() {
      // console.log('建仓：买入')
      this.idSowConfirm(1);
    }, 1000),
    sellOut: throttle(function() {
      // console.log('建仓：卖出')
      this.idSowConfirm(2);
    }, 1000),
    closeOut: throttle(function() {
      // console.log('建仓：平仓')
      this.idSowConfirm(3);
    }, 1000),
    // 下单是否弹出确认提示框
    idSowConfirm(otype) {
      if (this.handleClass.length && otype === 3) return;
      if (this.delogEve) {
        // 打开确认弹出框并将分类存储
        this.consbType = otype;
        this.orderTip = true;
        // 将当前下单的合约信息暂存
        let nowId = this.nowConCode;
        this.orderObj = this.contractlist.find((v) => v.heyue_id === nowId);

        if (otype === 1) {
          this.tradeType = this.$t("trade.buyPrice");
          if (this.priceType === "1") this.tipPrice = this.latestSell; // 对手价（最新卖价）
        }
        if (otype === 2) {
          this.tradeType = this.$t("trade.sellPrice");
          if (this.priceType === "1") this.tipPrice = this.latestBuy; // 对手价（最新买价）
        }
        if (otype === 3) {
          this.tradeType = this.$t("trade.closPrice");
          if (this.priceType === "1") this.tipPrice = this.latestBuy; // 对手价（最新买价）
        }
        if (this.priceType === "2")
          this.tipPrice = this.$t("trade.marketPrice"); // 当前市价
        if (this.priceType === "4") this.tipPrice = this.btnPrice; // 挂单价
        if (this.priceType === "5") this.tipPrice = this.nowPrice; // 手动价格
      } else {
        // 没有设置确认弹出提示框，直接调用
        this.orderTip = false;
        this.consbType = otype;
        this.handleBtns();
      }
    },
    // 买卖平仓按钮操作
    handleBtns() {
      // console.log('提交标志', this.priceTypeIcon)
      // console.time("建仓操作服务器响应耗时：");
      // console.time("建仓操作提示完毕耗时：");
      this.orderTip = false;
      let type = this.consbType;
      // 买、卖、平按钮操作
      let price = 0; // 当前要发送的给后台的价格
      if (this.isCal) {
        // 改变则传自定义价(委托价)
        price = this.nowPrice;
      } else {
        // 不改变传最新价
        price = this.latestSell;
      }

      if (this.priceType === "2" && !this.isCal) {
        // 市价加减，为委托价
        price = 0; // 不操作传0
      }
      // console.log("合约id:" + contractID);

      // 委托建仓(15) 发送：15;合约ID;数量;价格;买卖方向;IP地址;止盈点;止损点;
      // 15;525;1;12125;1;12;8;1.193.36.154;
      // 委托建仓 => 买
      if (type === 1) {
        // 根据选择的价格类型做处理, 对手价默认为相反，市价默认为0
        if (this.priceType === "1" && this.nowPrice === "" && !this.isCal) {
          // 当前类型为对手价，且用户未自定义价格
          price = this.latestSell; // 最新卖价
        }

        if (this.priceType === "4") {
          price = this.btnPrice;
        }
        //this.$store.dispatch("panel/playTipsAudio", 8);
        //this.$voice('02');
        console.log(
          "ws操作",
          `15;${this.nowConCode};${this.hands};${price};1;${this.stopScore};${this.stopLoss};0;${this.$store.getters.userip};`
        );
        trade.wsSend(
          //`15;${this.nowConCode};${this.hands};${price};1;${this.stopScore};${this.stopLoss};${this.priceTypeIcon};${this.$store.getters.userip};`
          `15;${this.nowConCode};${this.hands};${price};1;${this.stopScore};${this.stopLoss};0;${this.$store.getters.userip};`
        );
        this.hands = 1;
        //         this.stopScore = 0;
        //         this.stopLoss = 0;
      }

      // 委托建仓 => 卖
      if (type === 2) {
        if (this.priceType === "1" && this.nowPrice === "" && !this.isCal) {
          // 当前类型为对手价，且用户未自定义价格
          price = this.latestBuy; // 最新买价
        }

        if (this.priceType === "4") {
          price = this.btnPrice;
        }
        //this.$store.dispatch("panel/playTipsAudio", 7);
        //this.$voice('01');

        // this.$store.dispatch("bar/changeLoadings", {
        //   status: true,
        //   msg: this.$t("tip.placeWait")
        // });
        // 将数据更新到store中和提交给后台
        // console.log(
        //   `15;${contractID};${this.hands};${price};2;;${this.stopScore};${
        //     this.stopLoss
        //   };${this.$store.getters.userip} `
        // );
        trade.wsSend(
          //`15;${this.nowConCode};${this.hands};${price};2;${this.stopScore};${this.stopLoss};${this.priceTypeIcon};${this.$store.getters.userip} `
          `15;${this.nowConCode};${this.hands};${price};2;${this.stopScore};${this.stopLoss};1;${this.$store.getters.userip} `
        );
        this.hands = 1;
      }

      // 委托平仓(17) 发送：17;合约ID;数量;价格;买卖方向;明细ID;IP;
      // 委托平仓
      if (type === 3) {
        // 当前为disable,则不作任何操作
        // console.log("平");
        if (this.ponIndex === -1) {
          return;
        }
        if (this.posRadio === "1") {
          if (
            this.showPosList[this.ponIndex] !== undefined &&
            this.showPosList[this.ponIndex].CanBeFlat <= 0
          ) {
            return;
          }

          if (this.showPosList[this.ponIndex].ContractID !== this.nowConCode) {
            return;
          }
        } else {
          if (
            this.showCollectList[this.ponIndex] !== undefined &&
            this.showCollectList[this.ponIndex].CanBeFlat <= 0
          ) {
            return;
          }

          if (
            this.showCollectList[this.ponIndex].ContractID !== this.nowConCode
          ) {
            return;
          }
        }

        //this.$store.dispatch("panel/playTipsAudio", 3); // 平仓声音
        // 进行平仓
        // this.$store.dispatch("bar/changeLoadings", {
        //   status: true,
        //   msg: this.$t("tip.placeWait")
        // });

        // console.log(`17;${contractID};${this.hands};${price};${
        //     this.showPosList[this.ponIndex].BusCode
        //   };${this.showPosList[this.ponIndex].ID};${
        //     this.$store.getters.userip
        //   };`)

        if (this.priceType === "4") {
          price = this.btnPrice;
        } else {
          price = 0;
        }

        if (this.posRadio === "1") {
          //this.$store.dispatch("panel/playTipsAudio", 9);
          //this.$voice('03');
          let bz = this.showPosList[this.ponIndex].BusCode == 1 ? 1 : 0;
          trade.wsSend(
            `17;${this.nowConCode};${this.hands};${price};${
              this.showPosList[this.ponIndex].BusCode
            };${this.showPosList[this.ponIndex].ID};${bz};${
              this.$store.getters.userip
            };`
          );
        } else {
          //this.$store.dispatch("panel/playTipsAudio", 10);
          //this.$voice('04');
          let bz = this.showCollectList[this.ponIndex].BusCode == 1 ? 1 : 0;
          trade.wsSend(
            `17;${this.nowConCode};${this.hands};${price};${
              this.showCollectList[this.ponIndex].BusCode
            };0;${bz};${this.$store.getters.userip};`
          );
        }

        this.hands = 1;
      }
    },
    // 全部平仓 / 撤单
    operationAll(type) {
      if (this.showPosList.length === 0 && type === 1) {
        this.$store.dispatch("bar/switchAlert", {
          msg: this.$t("tip.noFlat"),
          type: 2,
        });
        return;
      }
      if (this.cancelList.length === 0 && type === 2) {
        this.$store.dispatch("bar/switchAlert", {
          msg: this.$t("tip.noReact"),
          type: 2,
        });
        return;
      }
      let sFields = "";
      if (type === 1) {
        // 全部平仓
        this.$store.dispatch("panel/playTipsAudio", 3);
        sFields = "29;" + this.$store.getters.userip + ";";
      } else if (type === 2) {
        // 全部撤单
        this.$store.dispatch("panel/playTipsAudio", 6);
        sFields = "30;" + this.$store.getters.userip + ";";
      }
      this.$store.dispatch("bar/changeLoadings", {
        status: true,
        msg: this.$t("tip.placeWait"),
      });
      trade.wsSend(sFields);
    },
    // 快捷平仓
    quickClosing(type) {
		// 在列表中双击平仓，如果设置中没有设置，则无法双击持仓单平仓
		if (!this.dbclickEve && type === 2) {
			return;
		}
		// 快捷平仓
		if (this.ponIndex === -1) {
			this.$store.dispatch("bar/switchAlert", {
				msg: this.$t("tip.selectQuickClose"),
				type: 2,
			});
			return;
		}
		this.$store.dispatch("panel/playTipsAudio", 3);

		this.$store.dispatch("bar/changeLoadings", {
			status: true,
			msg: this.$t("tip.placeWait"),
		});
	  
		let nowContract;
		
		if (this.posRadio === "1") {
			nowContract = this.sortshowPosList[this.ponIndex];
		}
		else{
			nowContract = this.sortshowCollectList[this.ponIndex];
		}
		//console.log(nowContract);
		let detailID ;
		// 如果为汇总信息，则明显id传0
		if (this.posRadio === "2") {
			detailID = "0";
		}
		else{
			detailID = nowContract.ID
		}

		// 委托平仓(17) 发送：17;合约ID;数量;价格;买卖方向;明细ID;IP;
		let busDir = nowContract.BusCode;
		if (busDir === "买") {
			busDir = "1";
		}
		if (busDir === "卖") {
			busDir = "2";
		}
		let bz = nowContract.BusCode == 1 ? 1 : 0;

		trade.wsSend(
			`17;${nowContract.ContractID};${nowContract.Quantity};0;${busDir};${detailID};${bz};${this.$store.getters.userip};`
		);
    },
    // 撤单
    withdrawal() {
      if (this.comIndex === -1) {
        this.$store.dispatch("bar/switchAlert", {
          msg: this.$t("tip.selectRevokeEntrust"),
          type: 2,
        });
        return;
      }

      this.$store.dispatch("panel/playTipsAudio", 6);
      this.$store.dispatch("bar/changeLoadings", {
        status: true,
        msg: this.$t("tip.placeWait"),
      });

      let nowData = this.cancelList[this.comIndex];

      // 委托单取消(16) 发送：16;委托单号;IP;
      trade.wsSend(`16;${nowData.Numbering};${this.$store.getters.userip};`);
    },
    // 快捷反手
    Backhand() {
		if (this.ponIndex === -1) {
			this.$store.dispatch("bar/switchAlert", {
				msg: this.$t("tip.selectReverseContract"),
				type: 2,
			});
			return;
		}
		
		let nowContract;
		
		if (this.posRadio === "1") {
			nowContract = this.sortshowPosList[this.ponIndex];
		}
		else{
			nowContract = this.sortshowCollectList[this.ponIndex];
		}
		
		let sendId // 明细id
		if (this.posRadio === "1") {
			sendId = nowContract.ID;
		}
		else{
			sendId = "0";
		}

		this.$store.dispatch("panel/playTipsAudio", 6);
		//  市价反手（32） 发送：32;合约ID;数量;价格;买卖方向;明细ID;IP;
		this.$store.dispatch("bar/changeLoadings", {
			status: true,
			msg: this.$t("tip.placeWait"),
		});
		let bz = nowContract.BusCode == 1 ? 1 : 0;
		trade.wsSend(
			`32;${nowContract.ContractID};${nowContract.Quantity};0;${nowContract.BusCode};${sendId};${bz};${this.$store.getters.userip};`
		);
    },
    // 快捷锁仓
    quickLock() {
		if (this.ponIndex === -1) {
			this.$store.dispatch("bar/switchAlert", {
				msg: this.$t("tip.selectQuickLock"),
				type: 2,
			});
			return;
		}
		
		// 判断当前买卖手数是否一致
		let nowContract;
		
		if (this.posRadio === "1") {
			nowContract = this.sortshowPosList[this.ponIndex];
		}
		else{
			nowContract = this.sortshowCollectList[this.ponIndex];
		}
		
		let buyQua = 0; // 买方向
		let sellQua = 0; // 卖方向
      // console.log(this.showCollectList);
		console.log("当前合约", nowContract);
	  
		for (const item of this.sortshowPosList) {
			// console.log(item);
			// 买方向
			if (item.ContractID === nowContract.ContractID &&item.BusCode === "1") {
				buyQua = buyQua + item.Quantity * 1;
			}
			// 卖方向
			if (item.ContractID === nowContract.ContractID &&item.BusCode === "2") {
				sellQua = sellQua + item.Quantity * 1;
			}
		}
		
		console.log("当前买数量", buyQua);
		console.log("当前卖数量", sellQua);

		// 判断买卖方向手数是否相等
		let count = null; // 锁仓需要补足的手数
		let direction = null; // 锁仓的方向
		// 买比卖多，需要建仓count手卖方向的合约单
		if (buyQua > sellQua) {
			count = Math.abs(buyQua - sellQua);
			direction = "2";
		}

		// 卖比买多，需要建仓多出来的count手买方向的合约单
		if (buyQua < sellQua) {
			count = Math.abs(sellQua - buyQua);
			direction = "1";
		}
		
		// 买卖一样多
		if (buyQua === sellQua) {
			this.$store.dispatch("panel/playTipsAudio", 1);
			this.$notify.info({
				position: "bottom-right",
				offset: 20,
				title: this.$t("tip.tip"),
				message: this.$t("tip.noLockout"),
				type: "warning",
			});
			return;
		}
		
		console.log("锁仓补足数量：", count);
		console.log("锁仓补足方向：", direction);
		this.$store.dispatch("panel/playTipsAudio", 6);
		this.$store.dispatch("bar/changeLoadings", {
			status: true,
			msg: this.$t("tip.placeWait"),
		});
		
		let bz = nowContract.BusCode == 1 ? 1 : 0;
		// 发送：15;合约ID;数量;价格;买卖方向;IP地址;止盈点;止损点;
		trade.wsSend(
			// `15;${nowContract.ContractID};${count};0;${direction};${this.$store.getters.userip};0;0;`
			`15;${nowContract.ContractID};${count};0;${direction};0;0;${bz};${this.$store.getters.userip};`
		);
    },
    // 更改标识
    editbiaoshi() {
      if (this.ponIndex === -1) {
        this.$store.dispatch("bar/switchAlert", {
          msg: this.$t("tip.selectQuickLock"),
          type: 2,
        });
        return;
      }
      let nowBiaoshi = this.biaoshi;
      // 判断当前买卖手数是否一致
      let nowID = this.showPosList[this.ponIndex].ID;
      this.$db.set("order" + nowID, { biaoshi: nowBiaoshi }).write();
      this.showPosList[this.ponIndex].Biaoshi = nowBiaoshi;
      return;
    },
    // 新增止盈止损
    handleAddSetlist() {
      this.addFlag = true;

      this.profitAmount = 0; // 止盈金额
      this.lossAmount = 0; // 止损金额
      this.profitPrice = 0; // 止盈价位
      this.stopPrice = 0; // 止损价位
      this.showPaL = true;
      // this.$store.commit("panel/SET_SWITCHFLAG", true);
    },
    handleChangeRadio(val) {
      if (val === "1") {
        store.dispatch("panel/updateposRadio", "1");
        if (this.ponIndex != -1) {
          this.$store.dispatch(
            "panel/updateIsbuy",
            this.showPosList[this.ponIndex].BusCode
          );
          if (this.isLock) {
            // 当前锁定，只改变table中的tr选中
            // this.ponIndex = i;
            // this.$store.dispatch("panel/updatePonIndex", i);
          } else {
            // 未锁定，同时改变
            // this.$store.commit("product/SET_ACTCONTRACT", item.ContractID);
            this.$store.dispatch(
              "product/updateActcontract",
              this.showPosList[this.ponIndex].ContractID
            );
            // this.ponIndex = i;
            if (this.showPosList[this.ponIndex].Quantity * 1 > 0) {
              this.hands = this.showPosList[this.ponIndex].Quantity;
            }
          }
        }
      } else {
        if (this.ponIndex > this.showCollectList.length - 1) {
          store.dispatch("panel/updatePonIndex", -1);
        }
        store.dispatch("panel/updateposRadio", "2");
        if (this.ponIndex != -1) {
          this.$store.dispatch(
            "panel/updateIsbuy",
            this.showCollectList[this.ponIndex].BusCode
          );
          if (this.isLock) {
            // 当前锁定，只改变table中的tr选中
            // this.ponIndex = i;
            // this.$store.dispatch("panel/updatePonIndex", i);
          } else {
            // 未锁定，同时改变
            // this.$store.commit("product/SET_ACTCONTRACT", item.ContractID);
            this.$store.dispatch(
              "product/updateActcontract",
              this.showCollectList[this.ponIndex].ContractID
            );
            // this.ponIndex = i;
            if (this.showCollectList[this.ponIndex].Quantity * 1 > 0) {
              this.hands = this.showCollectList[this.ponIndex].Quantity;
            }
          }
        }
      }
    },
    weituoChangeRadio(val) {
      this.weituo_flag = val;
    },
		//汇总止盈止损
		modifyTheStopLoss2() {
			// 弹出止盈止损列表
			this.addPoIndex = this.ponIndex;
			let len = this.sortshowCollectList.length - 1;
			if (this.ponIndex === -1 || this.ponIndex > len) {
				this.$store.dispatch("bar/switchAlert", {
					msg: this.$t("tip.selectLimitStop"),
					type: 2,
				});
			} 
			else {
				let arr = this.sortshowCollectList;
				let setOrder = arr[this.ponIndex]; // "552585"
				// let setId = setOrder.ID
				let setId   = setOrder.ContractID;
				//console.log('获取合约ID', setId, setOrder)
				let setCode = setOrder.BusCode;
				//trade.wsSend("35;0;0;"); // 35;合约ID;买卖方向
				//this.$store.dispatch("panel/updateSwitchFlag", false);
				/* this.$store.commit("panel/SET_SWITCHFLAG", false); */
				
				let Name = setOrder.Name;
				let AveragePrice = setOrder.AveragePrice;
				let temp_lists = this.fullstoplistsz.filter(item => item.ContractId === setOrder.ContractID && item.Business === setOrder.Business)
				let temp_lists1 = temp_lists.map(item=>{
					item.AveragePrice = AveragePrice 
					item.Name = Name
					return item
				})
				this.$store.commit("panel/SET_FULLSTOPLIST2", temp_lists1);
				
				let moduless = {
					moduleID: 0,
					Name: Name,
					ContractID: setId,
					AveragePrice: AveragePrice,
					BusCode: setCode,
				};

				this.$store.commit("panel/SET_MODULES2", moduless);
				
				// console.log('*************:', moduless, this.$store.getters.Modules)
				// this.settingListInit(setId, Name)
				this.showPalist = true;
			}
		},
		modifyTheStopLoss1() {
			// 弹出止盈止损列表
			this.addPoIndex = this.ponIndex;
			if (this.ponIndex === -1) {
				this.$store.dispatch("bar/switchAlert", {
					msg: this.$t("tip.selectLimitStop"),
					type: 2,
				});
			} 
			else {
				let arr = this.sortshowPosList;
			
				let setOrder = arr[this.ponIndex]; // "552585"
				let setId    = setOrder.ID;
				
				trade.wsSend("38;" + setId);
				this.$store.dispatch("panel/updateSwitchFlag", false);
			/* this.$store.commit("panel/SET_SWITCHFLAG", false); */
			let Name = setOrder.Name;
			let AveragePrice = setOrder.AveragePrice;
			let moduless = {
			  Name: Name,
			  ID: setId,
			  AveragePrice: AveragePrice,
			};
			this.$store.commit("panel/SET_MODULES", moduless);
			// console.log('*************:', moduless, this.$store.getters.Modules)
			// this.settingListInit(setId, Name)
			this.showPalist = true;
		  }
		},
    // 初始化止盈止损列表
    settingListInit(id, name) {
      let _list = [];
      trade.wsSend("38;" + id);
      let list = this.fullstoplist;
      let fullstopArray = Object.keys(list).map((key) => {
        return list[key];
      });
      fullstopArray = fullstopArray.filter((item) => item.ID !== undefined);
      let modules = this.showPosList[this.addPoIndex];
      //console.log('modules：', modules)
      for (let i = 0; i < fullstopArray.length; i++) {
        fullstopArray[i].Name = modules.Name;
        fullstopArray[i].AveragePrice = modules.AveragePrice;
      }
      // modules && modules.map((item) => {
      //   fullstopArray.push({
      //     Name: item.Name,
      //     AveragePrice: item.AveragePrice
      //   })
      // })
      //console.log('fullstopArray:', fullstopArray)
      _list = fullstopArray;
      //console.log("止盈止损列表0", _list)
      this.listData = _list;
    },
    // 删除止盈止损
    removeStopLoss(index) {
      // 发送：37;合约ID;买卖方向;数量;止盈点位;止损点位;止盈金额;止损金额;止盈止损类别;超价点数;明细ID;IP;
      // let ID = this.showPalist[this.addPoIndex].ID
      // console.log(this.addPoIndex)
      // this.$store.commit("panel/SET_SWITCHFLAG", true);
      let nowConData = this.fullstoplist2[index];
      let _selfId = nowConData.selfId;
      //   let Name = nowConData.Name
      //console.log("点击删除", _selfId)
      this.$store.commit("panel/SET_ISPLDEL", true);
      // console.log(ID)
      trade.wsSend("19;" + _selfId + ";");

      // this.fullstoplist.splice(index, 1)
      // trade.wsSend('38;'+ nowConData.ID + ';');
      //   this.settingListInit(ID, Name)
    },

    // 弹出修改止盈止损
    modifyTheStopLoss(index) {
      this.addFlag = false;
      //   if (this.ponIndex === -1) {
      //     this.$store.dispatch("bar/switchAlert", {
      //       msg: this.$t("tip.selectLimitStop"),
      //       type: 2
      //     });
      //     return;
      //   }
      let nowOrder = this.fullstoplist2[index];
      // let detId = nowOrder.selfId
      // 当前选中的合约如果有设置止盈止损，则将当前的止盈止损填入
      //Business: "买"
      // ContractId: "556"
      // ID: "500374"
      // LossAmount: 100
      // LossPoint: 2919.45
      // ProfitAmount: 108
      // ProfitPoint: 2924.34
      // Quantity: 1
      // Super: 100
      // Type: "0"
      // console.log('当前止盈止损列表:', this.fullstoplist)
      // console.log('当前合约：', nowOrder)
      // console.log('当前止盈止损', this.fullstoplist[detId])
      // this.fullstopId = 0
      //   if (this.fullstoplist[detId] !== undefined) {
      // this.profitAmount = this.fullstoplist[detId].ProfitAmount // 止盈金额
      // this.lossAmount = this.fullstoplist[detId].LossAmount // 止损金额
      // this.profitPrice = this.fullstoplist[detId].ProfitPoint // 止盈价位
      // this.stopPrice = this.fullstoplist[detId].LossPoint // 止损价位
      // this.fullstopId = this.fullstoplist[detId].selfId // 止损id
      // this.showPLdel = true;
      //   } else {
      //     this.showPLdel = false;
      //   }
      this.profitAmount = nowOrder.ProfitAmount; // 止盈金额
      this.lossAmount = nowOrder.LossAmount; // 止损金额
      this.profitPrice = nowOrder.ProfitPoint; // 止盈价位
      this.stopPrice = nowOrder.LossPoint; // 止损价位
      this.fullstopId = nowOrder.selfId; // 止损id
      this.showPLdel = false;

      this.$store.dispatch("panel/playTipsAudio", 6);
      this.showPaL = true;
      // 将当前选中的单子的持仓填入
      // <span>{{$t('trade.position')}}：{{showPosList[ponIndex] === undefined ? '' : showPosList[ponIndex].Quantity}}</span>
      this.quanNum = nowOrder ? Number(nowOrder.Quantity) : 0;
    },
    handlePage(val) {
      let vm = this;
      vm.currentPage1 = val;
      let curNum = val - 1;
      // console.log('val', this.fullfenyelist)
      let arrUpdate = this.fullfenyelist[curNum];
      this.$store.commit("panel/SET_FULLSTOPLIST2", arrUpdate);
    },
    handlePageSize(val) {
      let vm = this;
      vm.limit = val;
    },
    dialogClose() {
      this.showPaL = false;
      this.quanNum = 1;
    },
    dialogClose2() {
      this.showPalist = false;
      this.$store.dispatch("panel/updateSwitchFlag", true);
      let moduless = {};
      this.$store.commit("panel/SET_MODULES", moduless);
    },
    // 提交修改的止盈止损
    submitProfitLoss() {
      this.$store.dispatch("panel/updateSwitchFlag", true);
      this.plError = "";
      let latestP = 0; // 当前最新价
      if (this.posRadio === "1") {
        let nowId = this.showPosList[this.ponIndex].ContractID;
        let detailId = this.showPosList[this.ponIndex].ID;

        for (const item of this.latestMarket) {
          if (item.heyue_id === nowId) {
            latestP = item.currentPrice;
          }
        }
        // console.log("最新价", latestP * 1);
        // console.log("止损价", this.stopPrice * 1);
        // console.log("止盈价", this.profitPrice * 1);
        // 判断数量
        if (
          this.quanNum === 0 ||
          this.quanNum > this.showPosList[this.ponIndex].Quantity * 1
        ) {
          this.plError = this.$t("tip.contrast5"); // 持仓不能为零或大于本单的持仓数
          return;
        }
        // 买
        if (this.showPosList[this.ponIndex].BusCode === "1") {
          // 止损价 < 最新价
          // 止盈价 > 最新价
          if (this.stopPrice * 1 > latestP * 1 && this.stopPrice * 1 !== 0) {
            this.plError = this.$t("tip.contrast1");
            return;
          }
          if (
            this.profitPrice * 1 < latestP * 1 &&
            this.profitPrice * 1 !== 0
          ) {
            this.plError = this.$t("tip.contrast2");
            return;
          }
        }

        // 卖
        if (this.showPosList[this.ponIndex].BusCode === "2") {
          // 止损价 > 最新价
          // 止盈价 < 最新价
          if (this.stopPrice * 1 < latestP * 1 && this.stopPrice * 1 !== 0) {
            this.plError = this.$t("tip.contrast3");
            return;
          }
          if (
            this.profitPrice * 1 > latestP * 1 &&
            this.profitPrice * 1 !== 0
          ) {
            this.plError = this.$t("tip.contrast4");
            return;
          }
        }
      } else if (this.posRadio === "2") {
        let nowId = this.showCollectList[this.ponIndex].ContractID;
        let detailId = this.showCollectList[this.ponIndex].ID;

        for (const item of this.latestMarket) {
          if (item.heyue_id === nowId) {
            latestP = item.currentPrice;
          }
        }
        // console.log("最新价", latestP * 1);
        // console.log("止损价", this.stopPrice * 1);
        // console.log("止盈价", this.profitPrice * 1);
        // 判断数量
        if (
          this.quanNum === 0 ||
          this.quanNum > this.showCollectList[this.ponIndex].Quantity * 1
        ) {
          this.plError = this.$t("tip.contrast5"); // 持仓不能为零或大于本单的持仓数
          return;
        }
        // 买
        if (this.showCollectList[this.ponIndex].BusCode === "1") {
          // 止损价 < 最新价
          // 止盈价 > 最新价
          if (this.stopPrice * 1 > latestP * 1 && this.stopPrice * 1 !== 0) {
            this.plError = this.$t("tip.contrast1");
            return;
          }
          if (
            this.profitPrice * 1 < latestP * 1 &&
            this.profitPrice * 1 !== 0
          ) {
            this.plError = this.$t("tip.contrast2");
            return;
          }
        }

        // 卖
        if (this.showCollectList[this.ponIndex].BusCode === "2") {
          // 止损价 > 最新价
          // 止盈价 < 最新价
          if (this.stopPrice * 1 < latestP * 1 && this.stopPrice * 1 !== 0) {
            this.plError = this.$t("tip.contrast3");
            return;
          }
          if (
            this.profitPrice * 1 > latestP * 1 &&
            this.profitPrice * 1 !== 0
          ) {
            this.plError = this.$t("tip.contrast4");
            return;
          }
        }
      }

      // 将当前需要保存的止盈止损信息存起来 // this.showPosList[this.ponIndex].ID // 明细id

      this.$store.dispatch("bar/changeLoadings", {
        status: true,
        msg: this.$t("tip.placeWait"),
      });
      // 设置止盈止损（37）
      // 发送：37;合约ID;买卖方向;数量;止盈点位;止损点位;止盈金额;止损金额;止盈止损类别;超价点数;明细ID;IP;
      let nowConData =
        this.posRadio === "1"
          ? this.showPosList[this.ponIndex]
          : this.showCollectList[this.ponIndex];

      // 设置止盈止损（37）
      // 发送：37;合约ID;买卖方向;数量;止盈点位;止损点位;止盈金额;止损金额;止盈止损类别;超价点数;明细ID;IP;

      // // 先取消止盈止损
      // let cancelStr = `37;${nowConData.ContractID};${nowConData.BusCode};0;${
      //   this.profitPrice ? this.profitPrice : 0
      //   };${this.stopPrice ? this.stopPrice : 0};${
      //   this.profitAmount ? this.profitAmount : 0
      //   };${this.lossAmount ? this.lossAmount : 0};0;100;${nowConData.ID};${
      //   this.$store.getters.userip
      //   };`;
      // this.$store.commit("panel/SET_ISPLDEL", false);
      // trade.wsSend(cancelStr);
      // 再设置止盈止损
      // 18;持仓ID;止盈止损ID;合约ID;方向;数量;止盈点位;止损点位;止盈金额;止损金额;止盈止损类别;超价点数;IP;
      // 37;合约ID;买卖方向;数量;止盈点位;止损点位;止盈金额;止损金额;止盈止损类别;超价点数;明细ID;IP;

      // if(this.fullstoplist[nowConData.ID]){
      //     trade.wsSend(`19;${nowConData.ID};`);
      // }
      if (this.posRadio === "1") {
        if (!this.addFlag) {
          let fieldStr = `18;${nowConData.ID};${this.fullstopId};${
            nowConData.ContractID
          };${nowConData.BusCode};${this.quanNum};${
            this.profitPrice ? this.profitPrice : 0
          };${this.stopPrice ? this.stopPrice : 0};${
            this.profitAmount ? this.profitAmount : 0
          };${this.lossAmount ? this.lossAmount : 0};0;100;${
            this.$store.getters.userip
          };`;
          // console.log(fieldStr);
          trade.wsSend(fieldStr);
          this.showPaL = false;
          this.quanNum = 1;
        } else {
          let fieldStr = `18;${nowConData.ID};0;${nowConData.ContractID};${
            nowConData.BusCode
          };${this.quanNum};${this.profitPrice ? this.profitPrice : 0};${
            this.stopPrice ? this.stopPrice : 0
          };${this.profitAmount ? this.profitAmount : 0};${
            this.lossAmount ? this.lossAmount : 0
          };0;100;${this.$store.getters.userip};`;
          //console.log('新增', fieldStr);
          trade.wsSend(fieldStr);
          this.showPaL = false;
          this.quanNum = 1;
          trade.wsSend("38;" + nowConData.ID + ";");
        }
      } else if (this.posRadio === "2") {
        if (!this.addFlag) {
          let fieldStr = `18;0;${this.fullstopId};${nowConData.ContractID};${
            nowConData.BusCode
          };${this.quanNum};${this.profitPrice ? this.profitPrice : 0};${
            this.stopPrice ? this.stopPrice : 0
          };${this.profitAmount ? this.profitAmount : 0};${
            this.lossAmount ? this.lossAmount : 0
          };0;100;${this.$store.getters.userip};`;
          // console.log(fieldStr);
          trade.wsSend(fieldStr);
          this.showPaL = false;
          this.quanNum = 1;
        } else {
          let fieldStr = `18;0;0;${nowConData.ContractID};${
            nowConData.BusCode
          };${this.quanNum};${this.profitPrice ? this.profitPrice : 0};${
            this.stopPrice ? this.stopPrice : 0
          };${this.profitAmount ? this.profitAmount : 0};${
            this.lossAmount ? this.lossAmount : 0
          };0;100;${this.$store.getters.userip};`;
          console.log("新增", fieldStr);
          trade.wsSend(fieldStr);
          this.showPaL = false;
          this.quanNum = 1;
          trade.wsSend(
            "35;" + nowConData.ContractID + ";" + nowConData.BusCode + ";"
          );
        }
      }
    },
    conversion(e, type, isReg = false) {
      // e: input源参数或者传入准确的值
      // type : 1止盈价位 2止盈金额 3止损价位 4止损金额
      // isReg: 当前是否是上下调节调用的
      let value = e;
      // 如果当前是inputy源参
      if (!isReg) {
        value = e.target.value; // 值
      }

      let contract =
        this.posRadio === "1"
          ? this.showPosList[this.ponIndex]
          : this.showCollectList[this.ponIndex]; // 当前设置止盈止损的合约
      if (!contract) {
        //console.log("当前选中需要修改止盈止损的目标合约不存在");
        //console.log(contract);
        return;
      }
      let nums = contract.Quantity; // 总的持仓量
      let num = this.quanNum; // 持仓量
      let price = contract.AveragePrice; // 持仓均价
      let ls = contract.Multiplier; // 客户端合约乘数
      let miniNum = contract.Minimum; // 最小波动
      let busCode = contract.BusCode; // 合约买卖方向
      let point = 2; // 保留小数点后几位
      let computeRes = 0; //计算后的金额
      // console.log("当前最小波动为：", miniNum);
      // 计算保留小数点后几位
      if (miniNum !== 0 && Number(miniNum) % 1 !== 0) {
        point = Number(miniNum)
          .toString()
          .split(".")[1].length; // 小数点后几位
      }

      if (Number(miniNum) % 1 === 0) {
        point = 0;
      }

      // 各个合约根据买卖方向计算
      switch (type) {
        case 1:
          // 1止盈价位
          if (value == 0) {
            // 价位为0不参与计算
            this.profitAmount = 0;
            return;
          }
          if (busCode === "1") {
            computeRes = (value * 1 - price) * num * ls;
          }

          // 卖: (price - value) * num * ls
          if (busCode === "2") {
            computeRes = (price - value * 1) * num * ls;
          }

          this.profitAmount = parseFloat(computeRes.toFixed(point));
          break;
        case 2:
          // 2止盈金额
          // 买 price + (value/ls/num)
          if (busCode === "1") {
            computeRes = price + (value * 1) / ls / num;
          }

          // 卖: (price - value) * num * ls
          if (busCode === "2") {
            computeRes = price - (value * 1) / ls / num;
          }

          this.profitPrice = parseFloat(computeRes.toFixed(point));
          break;
        case 3:
          // 3 止损价位
          if (value == 0) {
            this.lossAmount = 0;
            return;
          }
          // 卖: (value - price) * num * ls
          if (busCode === "2") {
            computeRes = (value * 1 - price) * num * ls;
          }

          // 买: (price - value) * num * ls
          if (busCode === "1") {
            computeRes = (price - value * 1) * num * ls;
            // console.log('止损价格', computeRes, price, value, num, ls)
          }

          this.lossAmount = computeRes.toFixed(point);
          break;
        case 4:
          // 4止损金额
          // 卖 price + (value/ls/num)
          if (busCode === "2") {
            computeRes = price + (value * 1) / ls / num;
          }

          // 买: (price - value) * num * ls
          if (busCode === "1") {
            computeRes = price - (value * 1) / ls / num;
          }

          this.stopPrice = parseFloat(computeRes.toFixed(point));
          break;
      }
    },
    // 获取最新的止盈价位
    getPrice(amount, oldprice, type, des) {
      let contract =
        this.posRadio === "1"
          ? this.showPosList[this.ponIndex]
          : this.showCollectList[this.ponIndex]; // 当前设置止盈止损的合约
      if (!contract) {
        //console.log("当前选中需要修改止盈止损的目标合约不存在");
        //console.log(contract);
        return;
      }
      let num = this.quanNum; // 持仓量
      let price = contract.AveragePrice; // 持仓均价
      let ls = contract.Multiplier; // 客户端合约乘数
      let miniNum = Number(contract.Minimum); // 最小波动
      let busCode = contract.BusCode; // 合约买卖方向
      let point = 0;
      // 四舍五入后保留波动的小数位
      /* function ForDight(Dight, How) {
			  Dight = Math.round(Dight * Math.pow(10, How)) / Math.pow(10, How);
			  return Dight
			} */
      let minipoint = miniNum.toString().split(".")[1];
      point = minipoint ? minipoint.length : point; // 小数点后几位

      switch (type) {
        case 2:
          this.profitAmount = amount;
          /* if (amount == 0) {
					  this.profitPrice = 0
					  return
					} */
          if (busCode === "1") {
            // 计算最新的止盈价位 买
            // 持仓价 + （止盈金额 *1）/合约数/持仓数
            let newprice = price + (amount * 1) / ls / num;
            // console.log('newprice old', newprice, oldprice)
            if (num !== 1) {
              // console.log('持仓不为1：', newprice)
              this.profitPrice = parseFloat(newprice.toFixed(point));
            } else {
              if (des === 1) {
                // 向上
                if (Math.round((newprice - oldprice) / miniNum) !== 0) {
                  this.profitPrice = parseFloat(
                    (oldprice + miniNum).toFixed(point)
                  );
                  if (this.profitPrice == 0) {
                    this.profitAmount = 0;
                  }
                  // this.profitPrice = this.ForDight(this.profitPrice, )
                } else {
                  this.profitPrice = oldprice;
                }
              } else {
                // 向下
                if (Math.round((newprice - oldprice) / miniNum) !== 0) {
                  this.profitPrice = parseFloat(
                    (oldprice - miniNum).toFixed(point)
                  ); // 计算精度
                  if (this.profitPrice == 0) {
                    this.profitAmount = 0;
                  }
                } else {
                  this.profitPrice = oldprice;
                }
              }
            }
          } else if (busCode === "2") {
            // 卖
            let newprice = price - (amount * 1) / ls / num;
            if (num !== 1) {
              this.profitPrice = parseFloat(newprice.toFixed(point));
            } else {
              if (des === 1) {
                // 向上
                // console.log("止盈价位：", newprice)
                if (Math.round((newprice - oldprice) / miniNum) !== 0) {
                  this.profitPrice = parseFloat(
                    (oldprice - miniNum).toFixed(point)
                  );
                  if (this.profitPrice == 0) {
                    this.profitAmount = 0;
                  }
                } else {
                  this.profitPrice = oldprice;
                }
              } else {
                // 向下
                if (Math.round((newprice - oldprice) / miniNum) !== 0) {
                  this.profitPrice = parseFloat(
                    (oldprice + miniNum).toFixed(point)
                  );
                  if (this.profitPrice == 0) {
                    this.profitAmount = 0;
                  }
                } else {
                  this.profitPrice = oldprice;
                }
              }
            }
          }
          break;
        case 4:
          this.lossAmount = amount;
          /* if (amount == 0) {
					  this.stopPrice = 0
					  return
					} */
          if (busCode === "1") {
            // 计算最新的止损价位 买
            // 持仓价 - （止损金额 *1）/合约数/持仓数
            let newprice = price - (amount * 1) / ls / num;
            // console.log('newprice old', newprice, oldprice)
            if (num !== 1) {
              this.stopPrice = parseFloat(newprice.toFixed(point));
            } else {
              if (des === 1) {
                // 向上
                if (Math.round((newprice - oldprice) / miniNum) !== 0) {
                  this.stopPrice = parseFloat(
                    (oldprice + miniNum).toFixed(point)
                  );
                  if (this.stopPrice == 0) {
                    this.lossAmount = 0;
                  }
                } else {
                  this.stopPrice = oldprice;
                }
              } else {
                // 向下
                if (Math.round((newprice - oldprice) / miniNum) !== 0) {
                  this.stopPrice = parseFloat(
                    (oldprice - miniNum).toFixed(point)
                  );
                  if (this.stopPrice == 0) {
                    this.lossAmount = 0;
                  }
                } else {
                  this.stopPrice = oldprice;
                }
              }
            }
          } else if (busCode === "2") {
            let newprice = price + (amount * 1) / ls / num;
            if (num !== 1) {
              this.stopPrice = parseFloat(newprice.toFixed(point));
            } else {
              if (des === 1) {
                // 向上
                // console.log("止损价位：", newprice)
                if (Math.round((newprice - oldprice) / miniNum) !== 0) {
                  this.stopPrice = parseFloat(
                    (oldprice - miniNum).toFixed(point)
                  );
                  if (this.stopPrice == 0) {
                    this.lossAmount = 0;
                  }
                } else {
                  this.stopPrice = oldprice;
                }
              } else {
                // 向下
                if (Math.round((newprice - oldprice) / miniNum) !== 0) {
                  this.stopPrice = parseFloat(
                    (oldprice + miniNum).toFixed(point)
                  );
                  if (this.stopPrice == 0) {
                    this.lossAmount = 0;
                  }
                } else {
                  this.stopPrice = oldprice;
                }
              }
            }
          }
          break;
      }
    },
    // 上下箭头调节价位/金额增减
    regulation(type, isAdd) {
      // type : 1止盈价位 2止盈金额 3止损价位 4止损金额
      // isAdd: 1增0减

      let num = this.quanNum; // 持仓数量

      let polist = [];
      if (this.posRadio === "1") {
        polist = this.showPosList[this.ponIndex];
      } else {
        polist = this.showCollectList[this.ponIndex];
      }

      let ls = polist.Multiplier; // 合约乘数
      let miniNum = Number(polist.Minimum); // 最小波动
      let chicangPrice = polist.AveragePrice; // 持仓价
      let stepUnit = ls * miniNum * num; // 每增/减一次要计算的步长（1或者最小波动）

      let point = 1;

      if (miniNum != 0 && miniNum.toString().indexOf(".") != -1) {
        point = miniNum.toString().split(".")[1].length; // 小数点后几位
      }
      // console.log('最小波动小数后', point)

      // 价位按照最小波动为单位
      if (type === 1 || type === 3) stepUnit = miniNum;

      switch (type) {
        case 1:
          // 止盈价位
          let price1 = this.profitPrice * 1;
          if (isAdd) {
            // 增
            price1 = price1 == 0 ? chicangPrice + stepUnit : price1 + stepUnit;
          }
          if (!isAdd) {
            //  && price1 > 0
            // 减
            price1 = price1 == 0 ? chicangPrice - stepUnit : price1 - stepUnit;
          }
          price1 = parseFloat(price1).toFixed(point);
          price1 = parseFloat(price1);
          // console.log('当前止盈价位', price1)
          this.profitPrice = price1;
          if (this.profitPrice == 0) {
            // 价位为0 不参与换算 对应金额也为0
            this.profitAmount = 0;
          } else {
            this.conversion(price1, type, true);
          }
          break;
        case 2:
          // 止盈金额
          let amount1 = this.profitAmount * 1;
          this.oldProfitPrice = Number(this.profitPrice);
          if (isAdd) {
            // 增
            amount1 = amount1 + stepUnit;
          }
          if (!isAdd) {
            //  && amount1 > 0 止盈止损金额可以为负数
            // 减
            amount1 = amount1 - stepUnit;
          }
          amount1 = amount1.toFixed(point);
          amount1 = parseFloat(amount1);
          if (this.profitPrice == 0) {
            this.profitAmount = amount1;
            this.conversion(amount1, type, true);
          } else {
            if (isAdd) {
              this.getPrice(amount1, this.oldProfitPrice, 2, 1);
            } else {
              this.getPrice(amount1, this.oldProfitPrice, 2, 0);
            }
          }
          break;
        case 3:
          // 止损价位
          let price2 = this.stopPrice * 1;
          if (isAdd) {
            // 增
            price2 = price2 == 0 ? chicangPrice + stepUnit : price2 + stepUnit;
          }
          if (!isAdd) {
            // && price2 > 0
            // 减
            price2 = price2 == 0 ? chicangPrice - stepUnit : price2 - stepUnit;
          }
          price2 = parseFloat(price2).toFixed(point);
          price2 = parseFloat(price2);
          this.stopPrice = price2;
          if (this.stopPrice == 0) {
            // 价位为0 不参与换算 对应金额也为0
            this.lossAmount = 0;
          } else {
            this.conversion(price2, type, true);
          }
          break;
        case 4:
          // 止损金额
          let amount2 = this.lossAmount * 1;
          if (isAdd) {
            // 增
            amount2 = amount2 - stepUnit;
          }
          if (!isAdd) {
            //  && amount2 > 0 向下表示亏损越来越多
            // 减
            amount2 = amount2 + stepUnit;
          }
          amount2 = amount2.toFixed(point);
          amount2 = parseFloat(amount2);
          if (this.stopPrice == 0) {
            this.lossAmount = amount2;
            this.conversion(amount2, type, true);
          } else {
            if (isAdd) {
              this.getPrice(amount2, Number(this.stopPrice), 4, 1);
            } else {
              this.getPrice(amount2, Number(this.stopPrice), 4, 0);
            }
          }
          break;
      }
    },
    // 计算止盈止损金额

    // 计算持仓数量
    calcPostion(type) {
      this.profitAmount = 0; // 止盈金额
      this.lossAmount = 0; // 止损金额

      let contract = {};

      if (this.posRadio === "1") {
        contract = this.showPosList[this.ponIndex];
      } else if (this.posRadio === "2") {
        contract = this.showCollectList[this.ponIndex]; // 汇总
      }

      let price = contract.AveragePrice; // 持仓均价

      // type 1加 0减
      if (type === 1 && this.quanNum < contract.Quantity) {
        this.quanNum = this.quanNum + 1;

        // 买
        // （止盈价-持仓价）*合约乘数*数量=止盈金额
        // （持仓价-止损价）*合约乘数*数量=止损金额
        // 卖
        // （持仓价-止盈价）*合约乘数*数量=止盈金额
        // （止损价-持仓价）*合约乘数*数量=止损金额
      } else if (type === 0 && this.quanNum > 1) {
        this.quanNum = this.quanNum - 1;
      }

      let ls = contract.Multiplier; // 客户端合约乘数
      let busCode = contract.BusCode; // 合约买卖方向
      if (busCode == "1") {
        this.profitAmount =
          this.profitPrice * 1 == 0
            ? 0
            : ((this.profitPrice * 1 - price) * ls * this.quanNum).toFixed(2);
        this.lossAmount =
          this.stopPrice * 1 == 0
            ? 0
            : ((price - this.stopPrice * 1) * ls * this.quanNum).toFixed(2);
      } else if (busCode == "2") {
        this.profitAmount =
          this.profitPrice * 1 == 0
            ? 0
            : ((price - this.profitPrice * 1) * ls * this.quanNum).toFixed(2);
        this.lossAmount =
          this.stopPrice * 1 == 0
            ? 0
            : ((this.stopPrice * 1 - price) * ls * this.quanNum).toFixed(2);
      }
    },
    // 删除当前订单的止盈止损
    deletePL() {
      // 发送：37;合约ID;买卖方向;数量;止盈点位;止损点位;止盈金额;止损金额;止盈止损类别;超价点数;明细ID;IP;
      let nowConData = this.showPosList[this.ponIndex];
      let cancelStr = `18;${nowConData.ContractID};${nowConData.BusCode};0;${
        this.profitPrice ? this.profitPrice : 0
      };${this.stopPrice ? this.stopPrice : 0};${
        this.profitAmount ? this.profitAmount : 0
      };${this.lossAmount ? this.lossAmount : 0};0;100;${nowConData.ID};${
        this.$store.getters.userip
      };`;
      this.$store.commit("panel/SET_ISPLDEL", true);
      trade.wsSend(cancelStr);
      this.showPaL = false;
      this.quanNum = 1;
    },
  },
};
</script>

<style lang="scss" scoped>
.price {
  background-color: #000;
}

.order {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  height: 100%;

  .order-form {
    position: relative;
    width: 400px;
    height: calc(100% - 4px);
    border: #919b9c 1px solid;
    margin-left: 2px;

    .conlock {
      background: url("../../../assets/img/unlock.png") no-repeat center center;
      background-size: 16px 21px;
      width: 31px;
      height: 32px;
      margin: 0 5px;
      cursor: pointer;
    }

    .unlock {
      background: url("../../../assets/img/lock.png") no-repeat center center;
      background-size: 21px 21px;
    }

    .profit-loss {
      //	display: flex;

      //	.ml6 {
      //		margin-left: 6px;
      //}
    }

    .btn-goup {
      position: absolute;
      width: 97%;
      bottom: 24px;
      display: flex;
      justify-content: space-between;

      .handle-btn {
        width: 120px;
        height: 74px;
        text-align: center;
        font-size: 20px;
        font-family: sans-serif;
        position: relative;
        cursor: pointer;
        background-size: contain;
        .price-num {
          font-size: 16px;
          height: 30px;
          line-height: 30px;
          color: #333333;
        }

        .btn-msg {
          position: relative;
          height: 42px;
          line-height: 42px;
          font-family: PingFang-SC-Medium;
          font-weight: 600;
        }

        &.buy-price {
          color: #e60808;

          &:hover {
            border-color: #de9621;
          }
        }

        &.sell-price {
          color: #19c705;

          &:hover {
            border-color: #de9621;
          }
        }

        &.close-price {
          color: #0678db;

          &:hover {
            border-color: #de9621;
          }
        }

        &.buy-disable {
          // background: #eee;
          // color: #ccc;
          // border: 1px solid #cccaca;
          cursor: not-allowed;

          &:hover {
            border-color: #cccaca;
          }
        }
      }
    }
  }

  .folding-strip {
    width: 10px;
    height: 100%;
    border: 1px solid #104261;
    border-radius: 5px;
    cursor: pointer;
    margin: 0 2px;
    display: flex;
    justify-items: center;
    align-items: center;
    position: relative;

    .fold-icon {
      width: 5px;
      height: 8px;
      background: url("../../../assets/img/o-place-arrow.png") no-repeat top
        center;
      margin-left: 2px;
    }

    &.expand {
      .fold-icon {
        transform: rotateY(180deg);
      }
    }

    &:hover:before {
      position: absolute;
      content: "";
      left: 0;
      bottom: 0;
      right: 0;
      top: 0;
      border: 2px solid #fcce71;
      border-radius: 10px;
    }
  }

  .order-table {
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;

    .header-handle {
      display: flex;
      justify-content: space-between;
      padding: 3px 0px 4px 3px;

      .btn {
        width: 60px;
        height: 22px;
        display: inline-block;
        line-height: 22px;
        text-align: center;
        border-radius: 3px;
        font-size: 12px;
        background-image: url(../../../assets/img/small.png);
        cursor: pointer;
        color: #191a15;
        outline: none;
        margin-right: 3px;
        user-select: none;
        background-size: contain;
        &:hover {
          // border-color: #de9621;
          background-image: url(../../../assets/img/smallActive.png);
        }
      }

      .el-radio {
        margin-right: 12px;

        .el-radio__label {
          font-size: 12px;
        }
      }
    }

    .table-box {
      height: calc(100% - 27px);
      border: 1px solid #b1bbc0;
      border-right: 0;

      .red {
        color: red;
      }

      .green {
        color: green;
      }
    }

    .position {
      height: 50%;

      .header-handle {
        .el-input {
          width: 120px;
          font-size: 12px;
          height: 12px;
        }

        .right {
          padding-right: 18px;
        }
      }
    }

    .commission {
      height: 50%;
    }
  }
}

/deep/.ivu-form-item-content {
  margin-left: 0 !important;
}

.order-form {
  padding: 26px 5px;

  /deep/.ivu-form {
    display: flex;
  }

  /deep/.ivu-form-item {
    margin: 8px 0;
  }

  /deep/.ivu-form-item-label {
    text-align: left;
  }

  .right {
    width: 168px;
    height: 124px;
    margin-top: 9px;
    /deep/.ivu-form-item-label {
      padding: 0 7px;
      height: 30px;
      line-height: 30px;
    }
    /deep/.ivu-form-item-content {
      width: 100px;
    }

    .profit-loss {
      border: 1px solid #ccc;
      border-radius: 5px;
      position: relative;
      padding: 22px 4px 0 0;

      .stopCheckbox {
        padding: 0 5px;
        background-color: #fff;
        position: absolute;
        top: 0%;
        left: 50%;
        transform: translate(-50%, -50%);
      }

      .stopCheckboxActive {
        color: #3399ff;
      }

      /deep/.el-input-number--mini {
        width: 111px;
      }
    }
  }
  .left {
    .order-item {
      width: 222px;
    }
  }
  .selectContract {
    /deep/.ivu-form-item-content {
      position: relative;
      .conlock {
        position: absolute;
        right: 2px;
        border: 1px solid #99999a;
        border-radius: 0 5px 5px 0;

        background-color: #fff;
      }
    }
  }

  .order-item {
    display: flex;

    .select {
      display: flex;
      align-items: center;
      margin-top: 8px;
      width: 160px;
      justify-content: space-between;
      .selectBtn {
        padding: 6px;
        margin: 0 1px;
        line-height: 1;
      }

      .selectBtnActive {
        background-color: #0078d7;
        color: #fff;
        border-radius: 5px;
      }
    }
    .typePrice {
      width: 160px;
      height: 30px;
      border: 1px solid #bcc5cc;
      border-radius: 5px;
      line-height: 30px;
      text-align: center;
    }
    .pricetipbox {
      display: flex;
      align-items: center !important;

      /deep/.el-input-number {
        flex: 1;
        line-height: 28px;
      }

      /deep/.ivu-select-selection {
        height: 28px;
      }

      .tipbox1 {
        min-width: 60px;
        flex: 0.5 !important;
      }
    }
  }
}

.rightActive {
  /deep/.el-input-number__increase,
  /deep/.el-input-number__decrease {
    background-color: transparent !important;
    color: #a2a2a2 !important;
    font-size: 26px;
  }
  /deep/.is-disabled,
  /deep/.el-input__inner {
    background-color: transparent !important;
    border-color: #bdc5cc;
  }
}

.price {
  background-color: #000;
}

.order-form {
  width: 400px;
  border: 1px solid #919b9c;

  /deep/.ivu-form {
    display: flex;
  }

  .order-item {
    display: flex;
  }
}
.buy-price {
  background-image: url(../../../assets/img/mairu.png);
}
.sell-price {
  background-image: url(../../../assets/img/maichu.png);
}
.close-price {
  background-image: url(../../../assets/img/ping.png);
  .price-num {
    color: #aaa !important;
  }
}
.is-disabled {
  /deep/.ivu-form-item-label {
    color: #9a9a9a;
  }
}
.profit-loss {
  /deep/.el-input__inner {
    height: 100% !important;
  }
}
/deep/.ivu-select-disabled .ivu-select-selection {
  background-color: #fff;
  opacity: 1;
  cursor: not-allowed;
  color: #515a6e;
}
</style>
